JPA在Embeddable和EmbeddedId之间映射@ManyToOne

时间:2016-03-18 12:17:18

标签: java spring hibernate jpa spring-boot

我的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;
    ...
}

EmbeddedId

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

数据库DDL

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)
);

当我开始申请时,我收到以下错误:

  

引起:org.hibernate.AnnotationException:mappedBy引用一个未知的目标实体属性:com.foobar.entity.LogSearchHistory.logSearchHistoryAttrs中的com.foobar.entity.LogSearchHistoryAttr.logSearchHistrs

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

2 个答案:

答案 0 :(得分:12)

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

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

参考:JPA / Hibernate OneToMany Mapping, using a composite PrimaryKey

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

答案 1 :(得分:2)

OneToMany 部分:

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