Embeddable 和 EmbeddedId 之间的 JPA 映射 @ManyToOne
Posted
技术标签:
【中文标题】Embeddable 和 EmbeddedId 之间的 JPA 映射 @ManyToOne【英文标题】:JPA mapping @ManyToOne between Embeddable and EmbeddedId 【发布时间】:2016-07-05 04:41:30 【问题描述】:我的 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;
...
OneToMany
@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.logSearchHistory
我不确定为什么会收到此错误 - 映射看起来正确(对我来说)。我的这个映射有什么问题?谢谢!
【问题讨论】:
logSearchHistory
在LogSearchHistoryAttr
中在哪里?
@Ramanlfc - 它在 EmbeddedId 对象中。是否应该从那里取出并放入logSearchHistoryAttr
?
手动将 targetEntity 添加到您的 OneToMany 注释中。
【参考方案1】:
在OneToMany部分:
@OneToMany(mappedBy = "primaryKey.logSearchHistory", fetch = FetchType.EAGER)
private List<LogSearchHistoryAttr> logSearchHistoryAttrs;
【讨论】:
【参考方案2】:您将mappedBy
属性移动到可嵌入的主键中,因此该字段不再命名为logSearchHistory
,而是命名为primaryKey.logSearchHistory
。更改您的映射条目:
@OneToMany(mappedBy = "primaryKey.logSearchHistory", fetch = FetchType.EAGER)
private List<LogSearchHistoryAttr> logSearchHistoryAttrs;
参考:JPA / Hibernate OneToMany Mapping, using a composite PrimaryKey。
您还需要使主键类LogSearchHistoryAttrPK
可序列化。
【讨论】:
可以保留@ManyToOne
映射吗?我问是因为我收到错误:>错误:列 logsearchh8_.id 不存在
它还在我的测试中。以上是关于Embeddable 和 EmbeddedId 之间的 JPA 映射 @ManyToOne的主要内容,如果未能解决你的问题,请参考以下文章
Embeddable 和 EmbeddedId 之间的 JPA 映射 @ManyToOne
为啥我的带有@EmbeddedId 的实体不能在其对应的@Embeddable 类中使用LocalDateTime?