我正在尝试通过 JPA 使用一对一映射在 2 个表之间映射非主键列。OneToOne 没有在提到的列上执行连接,而是选择了 Id 字段。
下面是表结构:
人表 id (PK) 名称 学院
学院表 id (PK) clg_name 位置
位置表 ID (PK) loc_name
我需要分别使用列 location 和 loc_name 提供 College 和 Location 之间的 OneToOne 映射。我尝试使用@NaturalId、@MapsId 并提供参考列名称。它仍然使用 id 字段
//人
@Entity
@Table(name = "PERSON", schema = "DETAILS")
@SecondaryTables({
@SecondaryTable(name = "COLLEGE", schema = "DETAILS")
})
class Person{
Person(){
this.college = new College();
}
@Id
@Column(name = "ID", nullable = false)
private Long id;
@Column(name = "NAME", nullable = false)
private String name;
@Column(name = "COLLEGE_NAME", table = "COLLEGE", nullable = false)
private String college;
@OneToOne(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, mappedBy = "person")
@JoinColumn(name = "ID")
private College college;
//getter setters
}
//大学
@Entity
@Table(name = "COLLEGE", schema = "DETAILS")
class College{
College(){
}
@Id
@MapsId
@OneToOne()
@JoinColumn(name = "ID")
private Person person;
@OneToOne(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER, mappedBy = "college")
@JoinColumn(referencedColumnName = "LOC_NAME")
private Location location;
@Column(name = "LOCATION", nullable = false)
private String loc;
//getter setters
}
//地点
@Entity
@Table(name = "LOCATION", schema = "DETAILS")
class Location{
Location(){}
@Id
@Column(name = "ID")
private Long collegeId;
@MapsId
@OneToOne()
@JoinColumn(name = "LOC_NAME", referencedColumnName ="LOCATION", nullable = false, unique = true)
private College college;
@Column(name = "LOC_NAME", nullable = false)
private String locName;
//getter setters
}
在上面的代码中,我面临使用位置名称列的 OneToOne 映射问题。我通过查询“from Person p where p.id = :id”从 JPA 存储库中查询 Person 对象。
日志中为 1to1 映射生成的 JPA 查询似乎是
从 details.college 学院 0_ 左外连接中选择 details.location location1_ on college0_.id=location1_.locName where college0_.id=?
Error:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
Caused by: java.sql.SQLSyntaxErrorException: ORA-01722: invalid number
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447)
at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396)
at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951)
at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513)
如果我从 Location 中删除 @MapsId ,则会出现以下错误:
org.hibernate.AnnotationException: A Foreign key refering has the wrong number of column. should be 0