例如,我有一个级联到B的A类:
public class A{
private String id;
private Set<B> bs = new HashSet<B>(0);
@Id
@GenericGenerator(name = "seq_id", strategy = generators.SequenceIdGenerator")
@GeneratedValue(generator = "seq_id")
@COLUMN(name="id" unique = true, nullable = false, length = 28)
public void getId(){
return this.id;
}
@OneToMany(fetch = FetchType.LAZY, mappedBy = "A")
@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE, CascadeType.PERSIST})
public void getBs(){
return bs;
}
}
我有B,它有自己的id和一个包含来自A
的id的列public class B
String id;
String aId;
A a;
@Id
@GenericGenerator(name = "seq_id", strategy = "generators.SequenceIdGenerator")
@GeneratedValue(generator = "seq_id")
@Column(name = "ID", unique = true, nullable = false, length = 28)
public String getId() {
return this.id;
}
@Column(name = "A_ID", nullable = false, length = 28)
public String getAId() {
return aId;
}
public void setAId(String aId) {
this.aId = aId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "A_ID", nullable = false, insertable = false, updatable = false)
@MapsId("aId")
public Admission getAdmission() {
return this.admission;
}
public void setAdmission(Admission admission) {
this.admission = admission;
}
如何在保存A时自动分配aId?我想要设置aId,但我总是得到一个错误,表示A_ID不能设置为null。
谢谢!
答案 0 :(得分:1)
在使用带有共享映射的派生标识符时,您不仅需要在关系中放置@MapsId
anotation,还需要使用@Id
注释来引用引用关系id的字段。
了解如何操作(setter ommited):
public class B {
String id;
String aId;
A a;
@Id
@GenericGenerator(name = "seq_id", strategy = "generators.SequenceIdGenerator")
@GeneratedValue(generator = "seq_id")
@Column(name = "ID", unique = true, nullable = false, length = 28)
public String getId() {
return this.id;
}
@Id
public String getAId() {
return aId;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "A_ID", nullable = false)
@MapsId("aId")
public A getA() {
return this.a;
}
}
另一个错误是您将您的关系注释为updatable = false
和insertable = false
,使持久性提供程序忽略将此字段写入数据库。