开发者

Persisting objects with predefined identifiers in Hibernate

开发者 https://www.devze.com 2023-02-10 12:26 出处:网络
I am a bit confused how Hibernate actually work when persisting. So let me make to examples to try to clarify my confusion, example 1:

I am a bit confused how Hibernate actually work when persisting. So let me make to examples to try to clarify my confusion, example 1:

class A {
   @Id
   int id;
}

A a = new A();
a.id = 1;
em.persist(a);

This will work a object a will be pe开发者_开发问答rsisted with identifier 1.

Example 2:

class B {
   @Id
   int id;
   @OneToMany(cascade = CascadeType.ALL)
   @JoinColumn(name = "bId")
   Set<C> cs;
}

class C {
   @Id
   int id;
}


B b = new B();
b.id = 2;
C c = new C()
c.id = 3
Set<C> cs = new HashSet<C>();
cs.add(c);
b.cs = cs; 
em.persist(b);

This will almost work. What will happen is that both a and b are persisted with the correct identifiers 2 and 3. However in table C the bId will be empty?! Why?

Please don't say that I should use merge on an empty database, it's such a waste.

0

精彩评论

暂无评论...
验证码 换一张
取 消