我试图通过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映射问题。我正在通过查询“来自Person p,其中p.id =:id”,从JPA存储库中查询Person对象。
日志中为1对1映射生成的JPA查询似乎是
从details.college College0_中选择,左外部联接details.college0_.id = location1_.locName上的location location1_,其中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)
如果我从“位置”中删除@MapsId,则会收到以下错误消息:
org.hibernate.AnnotationException: A Foreign key refering has the wrong number of column. should be 0