Hibernate主键作为外键

时间:2018-05-25 08:43:25

标签: hibernate spring-boot jpa spring-data spring-data-jpa

我想创建一个引用另一个实体的列的ID。我有Currency课程和AuditSystem课程。 Currency具有简单的字符串ID,AuditSystem的ID应为Currency类型的对象。我正在玩@IdClass并使我的类实现Serializable,但无法弄清楚如何让它工作,因为我仍然会遇到错误。 我认为这是一个微不足道的问题,但实际上无法提出任何问题。

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "audit_system")
public class AuditSystem implements Serializable {

    @Id
    private Currency currency;
    private Float audit;
    private Timestamp created;
}

@Data
@NoArgsConstructor
@Entity
@Table(name = "currencies")
public class Currency implements Serializable {

    @Id
    private String code;
    private String name;
    private String icon;
    private Timestamp created = Timestamp.from(Instant.now());
}

如何正确映射这些实体?

1 个答案:

答案 0 :(得分:1)

我的假设是你仍然需要在AuditSystem中拥有它自己的@Id字段。并在这两个实体之间建立关系。像这样的东西

@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "audit_system")
public class AuditSystem implements Serializable {

    @Id
    private String code;

    @OneToOne
    @PrimaryKeyJoinColumn
    private Currency currency;

    private Float audit;
    private Timestamp created;
}


@Data
@NoArgsConstructor
@Entity
@Table(name = "currencies")
public class Currency implements Serializable {

    @Id
    private String code;

    @OneToOne(mappedBy="currency")
    private AuditSystem auditSystem;

    private String name;
    private String icon;
    private Timestamp created = Timestamp.from(Instant.now());
}

@PrimaryKeyJoinColumn应该在主键也是外键的情况下提供帮助 Hibernate doc @PrimaryKeyJoinColumn