我有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
}
这是我的服务类
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);
这是我的testplandao方法
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();
}
}
}
我面临的问题是hibernate在子表中插入新记录。我已经从saveOrUpdate更改为更新,仍然hibernate正在插入新的子记录。
我做错了什么?
答案 0 :(得分:0)
对于你的方法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();
}
在查询执行之前不应该关闭会话,所以你会得到SessionException而不是期望的testPlan
,并且hibernate会保存un-persist实体。
从this question,您可能会发现saveOrUpdate()
执行以下操作: