我有两个实体之间的一对一关联,但其中一个必须有两个@Id。一个是PRI,另一个是MUL。我如何声明复合ID,以及如何映射类?
@Entity
@Table(name = "PERSONS")
public class Person implements Serializable{
private static final long serialVersionUID = -3451407520028311143L;
@Id
@Column(name = "ID")
private Integer id;
@Column(name = "ADDRESS_ID")
private Integer addressId;
@Column(name ="NAME")
private String name;
@OneToOne(mappedBy= "person", cascade= CascadeType.ALL)
private Address address;
...
}
第二个类通过@IdClass注释
进行映射@Entity
@Table ( name = "ADDRESS" )
@IdClass(AddressKeys.class)
public class Address implements Serializable {
@Id
@Column ( name = "ID")
private Integer id;
@Id
@Column ( name = "PERSON_ID")
private Integer idPerson;
@Column ( name = "CITY" )
private String city;
@OneToOne(cascade= CascadeType.ALL)
@JoinColumn(name="PERSON_ID")
private Person person;
...
}
和id类
class AddressKeys implements Serializable{
private Integer id;
private Integer idPerson;
//getters and setters
@Override
public int hashCode() {
...
return result;
}
@Override
public boolean equals(Object obj) {
...
}
}
因此,当我尝试创建并保存记录时,我有下一个错误
无法在实体的映射中打开sessionRepeated列: hibernateMappedModels.base1.mappedClasses.oneToOne.Address列: PERSON_ID(应使用insert =" false" update =" false")映射 java.lang.NullPointerException at hibernateMappedModels.base1.Main.run(Main.java:45)at hibernateMappedModels.base1.Main.main(Main.java:24
我尝试将Id字段设置为unInsertable和unUpdatable,并且它正在工作,但我需要它们是可插入和可更新的;有没有可能做到这一点?
答案 0 :(得分:0)
我对你的映射感到困惑,并且不确定除了下面的简单映射之外还需要什么:如果我遗漏了某些内容,那么你需要扩展你的问题。在将列映射两次时会出现错误 - 一次是通过一对一,一次是作为简单属性。另外,我不确定为什么在地址上需要复合键。
@Entity
@Table(name = "PERSONS")
public class Person implements Serializable{
private static final long serialVersionUID = -3451407520028311143L;
@Id
@Column(name = "ID")
private Integer id;
@Column(name ="NAME")
private String name;
@OneToOne(mappedBy= "person", cascade= CascadeType.ALL)
private Address address;
}
@Entity
@Table ( name = "ADDRESS" )
public class Address implements Serializable {
@Id
@Column ( name = "ID")
private Integer id;
@Column ( name = "CITY" )
private String city;
@OneToOne(cascade= CascadeType.ALL)
@JoinColumn(name="PERSON_ID")
private Person person;
}