【问题标题】:JPA: Foreign key which only one from composite keyJPA:外键,只有一个来自复合键
【发布时间】:2021-07-23 10:39:09
【问题描述】:

我无法让复合主键和外键在 JPA 2/Hibernate 中工作。我正在尝试用 A 和 B 创建一个简单的场景:

CREATE TABLE Customer(
    customer_id uuid,
    employee_id int,
    created_at timestamp with time zone DEFAULT now(),
    
    CONSTRAINT customer_id_employee_id_pkey PRIMARY KEY (customer_id, employee_id),
    CONSTRAINT fk_owner_owner_id FOREIGN KEY (customer_id)
        REFERENCES public.owner (id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
)

我应该如何创建实体类?

我在下面尝试过

@EqualsAndHashCode
@Data
public class CustomerId implements Serializable {
    private UUID customerId;
    private Long employeeId;
}


@Data
@Entity
@IdClass(CustomerId.class)
@Table(name = "customer")
public class Customer implements Serializable {
    private static final long serialVersionUID = -234295442215152987L;

    @Id
    @Column(name = "customer_id")
    private UUID customerId;

    @Id
    @Column(name = "employee_id")
    private Long employeeId;

    @CreationTimestamp
    @Column(name = "created_at", insertable = false, updatable = false)
    private OffsetDateTime createdAt;
}

但我不确定应该在哪个类中映射作为外键的 customer_id。 请帮帮我

【问题讨论】:

    标签: jpa orm composite-key


    【解决方案1】:

    它应该这样工作

    @Data
    @Embeddable
    public class CustomerId implements Serializable {
        private UUID customerId;
        private Long employeeId;
    }
    
    
    @Data
    @Entity
    @Table(name = "customer")
    public class Customer implements Serializable {
        private static final long serialVersionUID = -234295442215152987L;
    
        @EmbeddedId
        @Column(name = "customer_id")
        private CustomerId customerId;
    
    
        @CreationTimestamp
        @Column(name = "created_at", insertable = false, updatable = false)
        private OffsetDateTime createdAt;
    }
    

    【讨论】:

      猜你喜欢
      • 2018-02-25
      • 1970-01-01
      • 2015-07-02
      • 1970-01-01
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 2019-04-22
      相关资源
      最近更新 更多