有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用临时对象创建持久对象

我有两个这样的映射:

<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) 个答案

  1. # 1 楼答案

    我想你想做的是:

    A a2 = (A)session.get(A.class, 1);
    
  2. # 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
    

    另请参见: