简体   繁体   English

非 PK 列来自嵌入式实体的 JPA/Hibernate OneToMany 关系

[英]JPA/Hibernate OneToMany relationship from Embedded entity by non-PK columns

JPA Model: JPA Model:

@Getter
@Setter
@Entity
@AllArgsConstructor
@NoArgsConstructor
@Table(name = "BASE_RECORD")
public class BaseRecord {

    @Id
    @Column(name = "DB_ID")
    public Long id;

    @Embedded
    public DeclarantRecord declarant;
}

@Getter
@Setter
@Embeddable
@AllArgsConstructor
@NoArgsConstructor
public class DeclarantRecord {

    @Column(name = "DECLARANT_ID")
    public String declarantId;

    @Column(name = "DECLARANT_IDE")
    public String identificationNumber;

    @Column(name = "DECLARANT_NAME")
    public String name;

    @OneToMany(mappedBy = "baseRecord", fetch = FetchType.EAGER)
    public List<DeclarantAddress> addresses;
}

@Getter
@Setter
@Entity
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "ADDRESS_RECORD")
public class DeclarantAddress {

    @Id
    @Column(name = "DB_ID")
    public Long id;

    @ManyToOne
    @JoinColumn(name = "PERS_ID", referencedColumnName = "DECLARANT_ID")
    public BaseRecord baseRecord;
}

When fetching a BaseRecord from DB by using a Spring Boot JPARepository , I receive the following exception:使用 Spring Boot JPARepository从数据库中获取BaseRecord时,我收到以下异常:

Caused by: org.hibernate.AnnotationException: referencedColumnNames(DECLARANT_ID) of DeclarantAddress.baseRecord referencing BaseRecord not mapped to a single property

I cannot understand what's wrong and moreover, if I inline the DeclarantRecord in the BaseRecord entity by declaring all the properties in there and moving the exact same relationship declaration in the BaseRecord class, everything works perfectly.我不明白出了什么问题,而且,如果我通过在其中声明所有属性并在BaseRecord class 中移动完全相同的关系声明来将DeclarantRecord内联到BaseRecord实体中,则一切正常。

The answer that worked for me:对我有用的答案:

Move @Column(name = "DECLARANT_ID") public String declarantId;移动@Column(name = "DECLARANT_ID") public String declarantId; to BaseRecord class.BaseRecord class。

The rest can stay the same. rest 可以保持不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM