简体   繁体   中英

How to copy the record in hibernate with new primary key?

我想将一个表的记录复制到同一张表中(除了将新记录与以前的记录值一起保存,这里的主键将自动递增),因此如何在休眠状态下进行操作(是否有像session.save这样的直接方法? (Obj)),而我正在使用Hibernate 4.1.12。

您可以尝试将所有主键列设置为null,然后将Session.Save(obj)设置为null。

Let us Consider:

  1. Your table name as 'TestTable' with primary key 'id' (key which needs to be auto incremented).
  2. Your Model Class is 'Test' which has a field 'id' mapped to 'id' column of table 'TestTable'.

You can achieve what you are looking for, using the following approach:

Test  test  = (Test) sessionFactory.getCurrentSession().createCriteria(Test.class).add(Restrictions.eq("id", id)).uniqueResult();
test.setId(null);
sessionFactory.getCurrentSession().saveOrUpdate(test);

Try this

Test  test  = (Test) sessionFactory.getCurrentSession().createCriteria(Test.class).add(Restrictions.eq("id", id)).uniqueResult();
Test t=new Test();
t.setName(test.getName());
t.setAge(test.getAge());
sessionFactory.getCurrentSession().save(t);

Or if your table has createddate or modified date fields change that two values and save.

Test  test  = (Test) sessionFactory.getCurrentSession().createCriteria(Test.class).add(Restrictions.eq("id", id)).uniqueResult();
test.setCreatedDate(new Date());
sessionFactory.getCurrentSession().save(test);

You can try evicting the previous object before saving the new object.

Test  test  = (Test) sessionFactory.getCurrentSession().createCriteria(Test.class).add(Restrictions.eq("id", id)).uniqueResult();
sessionFactory.getCurrentSession().evict(test);
test.setId(1);
sessionFactory.getCurrentSession().save(test);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM