JPA:外键只有一个来自复合键

问题描述

我无法在 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 这是一个外键。 请帮帮我

解决方法

它应该这样工作

@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;
}