Hibernate saveOrUpdate

时间:2012-11-30 20:27:14

标签: hibernate

我有2个表(Customer和CustomerTemp)具有相同的列。 我正在从Customer表中检索记录并添加到CustomerTemp表。检索到的记录存储为custDetails对象。 我正在使用以下API:

 void saveOrUpdate(String entityName,
                  Object object)

我已使用@Entity Annotation声明了2个实体,即Customer和CustomerTemp。实体名称用于saveOrUpdate API。

session.saveOrUpdate("CustomerTemp", custDetails); 

将相同记录添加/更新到CustomerTemp表中。不知何故,hibernate在Customer表中添加/更新记录。

根据文档,hibernate应该向CustomerTemp表添加记录。不确定缺少什么。

更新

出于测试目的,我创建了2个表(table1和表2)

@Entity(name="mytable1")
public class table1 implements Serializable {
    private static final long serialVersionUID = 3627342236515154416L;

    @Id
    @GeneratedValue
    private int id;

    @Column(length=20)
    private String Name;
          // Getters and setters...
}

@Entity(name="mytable2")
public class table2 implements Serializable {

    private static final long serialVersionUID = -2203149737718957786L;

    @Id
    @GeneratedValue
    private int id;

    @Column(length=20)
    private String Name;
          // Getters and setters...
}

现在我使用table1创建了对象,并尝试将saveOrUpdate与myTable2实体一起使用,期望该记录将保存在table2中。但是,无论saveOrUpdate中提供的实体名称如何,记录始终保持为table1。

    Session session = getSessionFactory().getCurrentSession();  
    Transaction tx ;

    table1 tb1 = new table1();
    tb1.setName("Shirish");
    tx = session.beginTransaction();
    session.saveOrUpdate("mytable2", tb1);
    tx.commit();

此致    - Shirish

1 个答案:

答案 0 :(得分:0)

我可以通过克隆java对象来使用指定的方法。 table1是克隆来创建新的table2对象。但这是一个非常复杂的过程,涉及多个* -to-Many关系。

后来我尝试使用XML方法在hibernate中定义表。请参阅
Mapping same POJO to more than one table in Hibernate XML mapping files了解详情。请注意,在其他数据库操作中使用session.clear()之前,您可能需要使用session.clear()去实体化。

欢迎任何其他方法。

在这种情况下,克隆不需要,因为我们正在基于相同的Java对象定义表。

此致

希里什