嵌入式和嵌入式ID之间的JPA映射@ManyToOne

2022-09-01 17:33:06

我在Spring Boot JPA应用程序中进行了以下设置:

嵌入

@Embeddable
public class LogSearchHistoryAttrPK {
    @Column(name = "SEARCH_HISTORY_ID")
    private Integer searchHistoryId;

    @Column(name = "ATTR", length = 50)
    private String attr;

    @ManyToOne
    @JoinColumn(name = "ID")
    private LogSearchHistory logSearchHistory;
    ...
}

嵌入式Id

@Repository
@Transactional
@Entity
@Table(name = "LOG_SEARCH_HISTORY_ATTR")
public class LogSearchHistoryAttr implements Serializable {
    @EmbeddedId
    private LogSearchHistoryAttrPK primaryKey;

    @Column(name = "VALUE", length = 100)
    private String value;
    ...
}

一对多

@Repository
@Transactional
@Entity
@Table(name = "LOG_SEARCH_HISTORY")
public class LogSearchHistory implements Serializable {
    @Id
    @Column(name = "ID", unique = true, nullable = false)
    private Integer id;

    @OneToMany(mappedBy = "logSearchHistory", fetch = FetchType.EAGER)
    private List<LogSearchHistoryAttr> logSearchHistoryAttrs;
    ...
}

数据库滴滴涕

CREATE TABLE log_search_history (
    id serial NOT NULL,
    ...
    CONSTRAINT log_search_history_pk PRIMARY KEY (id)
 );

CREATE TABLE log_search_history_attr (
    search_history_id INTEGER NOT NULL,
    attr CHARACTER VARYING(50) NOT NULL,
    value CHARACTER VARYING(100),
    CONSTRAINT log_search_history_attr_pk PRIMARY KEY (search_history_id, attr),
    CONSTRAINT log_search_history_attr_fk1 FOREIGN KEY (search_history_id) REFERENCES
        log_search_history (id)
);

当我去启动应用程序时,我收到以下错误:

Caused by: org.hibernate.AnnotationException: mappedBy reference a unknown target entity property: com.foobar.entity.LogSearchHistoryAttr.logSearchHistory in com.foobar.entity.LogSearchHistoryAttrs

我不确定为什么我会收到此错误 - 映射看起来正确(对我来说)。我的这个映射有什么问题?谢谢!


答案 1

已将属性移动到可嵌入的主键中,因此该字段不再命名,而是 。更改您的映射依据条目:mappedBylogSearchHistoryprimaryKey.logSearchHistory

@OneToMany(mappedBy = "primaryKey.logSearchHistory", fetch = FetchType.EAGER)
private List<LogSearchHistoryAttr> logSearchHistoryAttrs;

参考:JPA / Hibernate OneToMany Mapping,使用复合 PrimaryKey

您还需要使主键类可序列化。LogSearchHistoryAttrPK


答案 2

OneToMany部分:

@OneToMany(mappedBy = "primaryKey.logSearchHistory", fetch = FetchType.EAGER)
private List<LogSearchHistoryAttr> logSearchHistoryAttrs;

推荐