[英]Hibernate saveOrUpdate does not update instead creates new record
I have 2 tables mapped bidirectional as follows 我有2个表双向映射如下
@Entity
@Table(name="testplan")
public class TestPlan {
@Id
@Column(name="testplan_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int testplan_id;
@OneToMany(mappedBy="testplan_id",cascade=CascadeType.ALL)
private List<TestPlanDetails> testPlanDetails;
//getters and setters
}
@Entity
@Table(name="TestPlanDetails")
public class TestPlanDetails {
@Id
@Column(name="testplan_details_id")
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int testplan_details_id;
@ManyToOne(cascade=CascadeType.ALL)
@JoinColumn(name="testplan_id")
private TestPlan testplan_id;
// getters and setters
}
this is my service class 这是我的服务班
TestPlan testPlan=testPlanDao.getTestPlan(id, testPlanVersion);
//saveGeneralInfo(rgi, testPlan);
TestPlanGeneralInfo tpgi=testPlanGeneralInfo(rgi, testPlan);
List<TestPlanDetails> testPlanDetails=getDetails(list,testPlan);
testPlan.setTestPlanDetails(testPlanDetails);
testPlanDao.updateTestPlan(testPlan);
this is my testplandao methods 这是我的测试计划方法
public TestPlan getTestPlan(int id,String testPlanVersion )
{
String hql="from TestPlan tp where tp.id=:id and tp.testplan_version=:testPlanVersion";
Query query=currentSession().createQuery(hql);
query.setParameter("id", id);
query.setParameter("testPlanVersion", testPlanVersion);
closeSession();
return (TestPlan) query.uniqueResult();
}
@Override
public void updateTestPlan(TestPlan tp)
{
// TODO Auto-generated method stub
Session session=currentSession();
Transaction tx=null;
try{
tx=session.beginTransaction();
session.saveOrUpdate(tp);
session.flush();
session.clear();
tx.commit();
}
catch(HibernateException eq)
{
tx.rollback();
eq.printStackTrace();
}
catch(Exception e)
{
tx.rollback();
e.printStackTrace();
}
finally
{
if (session != null && session.isOpen()) {
session.close();
}
}
}
The problem I am facing is hibernate is inserting new records in child table. 我面临的问题是休眠状态是在子表中插入新记录。 I have changed from saveOrUpdate to update, still hibernate is inserting new child records .
我已从saveOrUpdate更改为更新,但仍处于休眠状态,正在插入新的子记录。
What am I doing wrong? 我究竟做错了什么?
For your method getTestPlan, 对于您的方法getTestPlan,
public TestPlan getTestPlan(int id,String testPlanVersion )
{
String hql="from TestPlan tp where tp.id=:id and tp.testplan_version=:testPlanVersion";
Query query=currentSession().createQuery(hql);
query.setParameter("id", id);
query.setParameter("testPlanVersion", testPlanVersion);
closeSession();
return (TestPlan) query.uniqueResult();
}
Session shouldn't be closed before query execute, so you would get SessionException but not expected testPlan
, and hibernate save the un-persist entity. 在执行查询之前不应该关闭会话,因此您将获得SessionException而不是预期的
testPlan
,并休眠保存非持久实体。
From this question , you may find that saveOrUpdate()
does the following: 从这个问题中 ,您可能会发现
saveOrUpdate()
执行以下操作:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.