gpt4 book ai didi

java - hibernate @EmbeddedId

转载 作者:太空宇宙 更新时间:2023-11-04 13:56:25 25 4
gpt4 key购买 nike

这是我的问题

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: insert into table (code1, code2) values (?, ?) SQL Error: 1400, SQLState: 23000 ORA-01400: cannot insert NULL into "table"."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: insert into table (code1, code2) values (?, ?) SQL Error: 1400, SQLState: 23000 ORA-01400: cannot insert NULL into ("TABLE"."A_ID")

已解决

问题出在这里:

, insertable = false)

因此,hibernate生成没有a_id字段的sql,导致错误

最佳答案

它似乎不是来自复合id,而是来自A。尝试保存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);

关于java - hibernate @EmbeddedId,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29774672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com