使用瞬态对象创建持久对象

时间:2011-02-07 01:12:51

标签: java hibernate persistence hibernate-mapping

我有2个像这样的映射:

<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>  

这些是类:

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<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; }  
}  

我正处于一个需要处理长时间转换并执行以下操作的情况:

// 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();  

这发生在另一层(无法访问会话):

// * 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 *  

在保存父对象之前是否有任何方法加载/获取持久子对象?还是有其他方法来保存子对象而不更改信息并将其全部冲洗?我没有使用JPA。对不起,如果我错了。

谢谢。

2 个答案:

答案 0 :(得分:2)

目前新孩子的状态未保存到数据库中,因为您的关系没有级联,因此孩子的错误状态应该不是一个大问题。

但是,如果您希望内存中的实体具有一致的状态,则可以使用merge()代替save(),而无需级联,它应该完全符合要求:

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

另见:

答案 1 :(得分:0)

我认为你想要做的是:

A a2 = (A)session.get(A.class, 1);