问题描述
我在 Spring Boot JPA 应用程序中有以下设置:
I have the following setup in my Spring Boot JPA application:
可嵌入
@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)
);
当我去启动应用程序时,出现以下错误:
When I go to start the application, I get the following error:
引起:org.hibernate.AnnotationException:mappedBy 引用了一个未知的目标实体属性:com.foobar.entity.LogSearchHistory.logSearchHistoryAttrs 中的 com.foobar.entity.LogSearchHistoryAttr.logSearchHistory
我不知道为什么我会收到这个错误 - 映射看起来是正确的(对我来说).我的这个映射有什么问题?谢谢!
I am not sure why I am getting this error - the mapping looks correct (to me). What is wrong with this mapping that I have? Thanks!
推荐答案
您将 mappedBy
属性移动到可嵌入的主键中,因此该字段不再命名为 logSearchHistory
而是 primaryKey.logSearchHistory
.更改您的映射条目:
You moved the mappedBy
attribute into an embeddable primary key, so the field is no longer named logSearchHistory
but rather primaryKey.logSearchHistory
. Change your mapped by entry:
@OneToMany(mappedBy = "primaryKey.logSearchHistory", fetch = FetchType.EAGER)
private List<LogSearchHistoryAttr> logSearchHistoryAttrs;
参考:JPA/Hibernate OneToMany 映射,使用复合主键.
您还需要使主键类 LogSearchHistoryAttrPK
可序列化.
You also need to make the primary key class LogSearchHistoryAttrPK
serializable.
这篇关于JPA 在 Embeddable 和 EmbeddedId 之间映射@ManyToOne的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!