JPA,Composite Key 由外键和表列成员组成
Posted
技术标签:
【中文标题】JPA,Composite Key 由外键和表列成员组成【英文标题】:JPA, Composite Key consisted of foreign key and table column members 【发布时间】:2018-08-08 13:47:31 【问题描述】:向社区致以问候,
我整天都在努力寻找解决以下问题的方法。
场景如下,我有一张桌子
---TABLE_ONE---
INT ID
VARCHAR NAME
PRIMARY_KEY (ID)
我的另一个表由三列组成,它们共同组成一个复合键
---TABLE_TWO---
INT TABLE_ONE_ID (FK -> TABLE_ONE.ID)
VARCHAR NAME
VARCHAR EMAIL
PRIMARY_KEY(TABLE_ONE_ID, NAME, EMAIL)
我想要实现的关系是TABLE_ONE
实体将
拥有来自TABLE_TWO
的对象列表(一对多关系)。
我尝试这样做,如下所示。
@Entity
@Table(name = "TABLE_ONE")
public class TableOne
@Column(name="id")
private int id;
@Column(name="name")
private String name
@OneToMany(fetch = FetchType.EAGER, mappedBy = "tableOne")
private List<TableTwo> tableTwoList;
//getters, setters, constructors
@Entity
@Table(name = "TABLE_TWO")
public class TableTwo
@EmbeddedId
private TableTwoCompositeId tableTwoCompositeId;
@ManyToOne
@JoinColumn(name = "TABLE_ONE_ID", referencedColumnName = "ID", insertable = false, updatable = false)
private TableOne tableOne;
//getters, setters, constructors
@Embeddable
public class TableTwoCompositeId
@Column(name = "TABLE_ONE_ID")
public Integer provider;
@Column(name = "NAME")
public String name;
@Column(name = "EMAIL")
public String email;
//getters, setters, constructors
但是,当从数据库中检索 TableOne 对象时,我得到了 javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
和 Caused by: java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
。
提前感谢您的帮助!
【问题讨论】:
【参考方案1】:我认为您需要进行一些小改动:
TableOne.id
需要一个 @Id
注释
TableTwoCompositeId.provider
的类型应该与TableOne.id
的类型匹配
TableTwo.tableOne
需要一个 @MapsId
注释来指示它映射 TableTwoCompositeId.provider
以下是代码的外观:
@Entity
@Table(name = "TABLE_ONE")
public class TableOne
@Id
@Column(name="id")
private int id;
@Column(name="name")
private String name
@OneToMany(fetch = FetchType.EAGER, mappedBy = "tableOne")
private List<TableTwo> tableTwoList;
//getters, setters, constructors
@Entity
@Table(name = "TABLE_TWO")
public class TableTwo
@EmbeddedId
private TableTwoCompositeId tableTwoCompositeId;
@MapsId("provider") // maps provider attribute of embedded id
@ManyToOne
@JoinColumn(name = "TABLE_ONE_ID", referencedColumnName = "ID", insertable = false, updatable = false)
private TableOne tableOne;
//getters, setters, constructors
@Embeddable
public class TableTwoCompositeId
@Column(name = "TABLE_ONE_ID")
public int provider;
@Column(name = "NAME")
public String name;
@Column(name = "EMAIL")
public String email;
//getters, setters, constructors
【讨论】:
感谢您的回复。我做了您建议的更改,但 ListUnable to evaluate the expression Method threw 'org.hibernate.exception.SQLGrammarException' exception.
以上是关于JPA,Composite Key 由外键和表列成员组成的主要内容,如果未能解决你的问题,请参考以下文章