这是我的问题
IdComposite
上课:
@Embeddable
public class IdComposite implements Serializable{
@Column(name = "code1", nullable = false)
private String code1;
@Column(name = "code2", nullable = false)
private String code2;
// getters, setters, hashCode & equals
}
MyEntity
上课:
@Entity
@Table(name = "table")
public class MyEntity {
@EmbeddedId
private IdComposite comId;
@ManyToOne(fetch = FetchType.LAZY, cascade = {})
@JoinColumn(name = "a_id", nullable = false, updatable = false, insertable = false)
private A a;
// constructors, getters setters, e t.c.
}
DaoClass
片段:
MyEntity myEntity = new MyEntity();
A a = new A();
a.setId(5);
myEntity.setA(a);
IdComposite id = new IdComposite();
id.setCode1("1");
id.setCode2("2");
myEntity.setComId(id);
getSession().save(myEntity);
Hibernate结果:
Hibernate:插入表(code1,code2)值(?,?)SQL错误: 1400,SQLState:23000 ORA-01400:无法插入NULL “表”。 “A_ID”)
有什么问题?
编辑:
好的,我已经用这种方式更改了代码:
MyEntity
上课:
@Entity
@Table(name = "table")
public class MyEntity {
@EmbeddedId
private IdComposite comId;
@Column(name = "a_id", nullable = false, updatable = false, insertable = false)
private Long aId;
// constructors, getters setters, e t.c.
}
DaoClass
片段:
MyEntity myEntity = new MyEntity();
Long aId = 5L;
A a = (A) getSession().get(A.class, aId);
if (a == null || a.getId() != 5) { return }
myEntity.setAId(a.getId());
IdComposite id = new IdComposite();
id.setCode1("1");
id.setCode2("2");
myEntity.setComId(id);
getSession().save(myEntity);
Hibernate结果:
Hibernate:插入表(code1,code2)值(?,?) SQL错误:1400,SQLState:23000 ORA-01400:无法插入NULL(“TABLE”。“A_ID”)
解决
问题在于:
, insertable = false)
因此,hibernate生成的sql没有导致错误的a_id字段
答案 0 :(得分:0)
它似乎不是来自复合ID,而是来自A.尝试保存实例
MyEntity myEntity = new MyEntity();
A a = new A();
a.setId(5);
a= getSession().save(a);
myEntity.setA(a);
IdComposite id = new IdComposite();
id.setCode1("1");
id.setCode2("2");
myEntity.setComId(id);
getSession().save(myEntity);