Create a persistent object using a transient one
I have 2 mappings like this:
<hibernate-mapping>
<class name="A" table="A">
<id name="code" column="aCode" type="integer">
<generator class="assigned"/>
</id>
<property name="info" type="integer"/>
<set name="Bs" lazy="false">
<key>
<column name="aCode" not-null="true"/>
</key>
<one-to-many class="B"/>
</set>
</class>
<class name="B" table="B">
<id name="code" column="bCode" type="integer">
<generator class="assigned"/>
</id>
<many-to-one name="a"/>
</class>
</hibernate-mapping>
These are the classes:
public class A {
private int code;
private int info;
private Set<B> bs = new HashSet<B>(0);
public A() {};
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public int getInfo() { return info; }
public void setInfo(int info) { this.info = info; }
public Set<B> getBs() { return bs; }
public void setBs(Set&开发者_如何学Pythonlt;B> bs) { this.bs = bs; }
}
public class B {
private int code;
private A a;
public B() {};
public int getCode() { return code; }
public void setCode(int code) { this.code = code; }
public A getA() { return a; }
public void setA(A a) { this.a = a; }
}
I'm in a scenario where I have to deal with a long transition and do the following:
// Persistence Layer
Session session = factory.getCurrentSession();
session.beginTransaction();
A a1 = new A(); // Create transient object
a1.setCode(1);
a1.setInfo(10);
session.save(a1); // Persist it
// Something happening in another layer (see below)
// Continuing with the transaction
Object b = ... // Recover object
session.save(b); // Persist it using transient a2 object as a link but don't change/update its data
System.out.println(b.getA().getInfo()); // Returns 0 not 10;
session.commit();
This happens in another layer (don't have access to the session here):
// * Begin in another layer of the application *
A a2 = new A(); // Create another transient object same *code* as before
a2.setCode(1);
B b = new B(); // Create another transient object
b.setCode(1);
b.set(a2);
// * End and send the b Object to the persistence layer *
Is there any way load/get the persistent child object before saving parent one or is there other way to save the child object without change the info and flush it all? I'm not using JPA. Sorry if I'm terrible wrong.
Thank you.
Currently state of the new child is not saved into the database since your relationship doesn't have cascading, so wrong state of the child shouldn't be a big problem.
However, if you want to have consistent state of the entities in memory, you can use merge()
instead of save()
, without cascading it should work exactly as desired:
b = session.merge(b); // Persist it using transient a2 object as a link but don't change/update its data
System.out.println(b.getA().getInfo()); // Should return 10
See also:
- Hibernate: will merge work with many-to-one object transtively?
I think what you want to do is:
A a2 = (A)session.get(A.class, 1);
精彩评论