Hibernate session.update插入行而不是更新行

时间:2019-04-21 11:06:46

标签: java hibernate

Event.hbm.xml与战斗有一对多的关系

<class name="Event" table="event">
  <id name="oid" type="long" column="oid">
  <generator class="increment">
     <param name="initial_value">1</param>
  </generator>
  </id>
<property name="address">
  <column name="address"/>
</property>
<property name="date">
   <column name="date"/>   
</property>
  <list name="fights" cascade="all">  
          <key column="eventOid"></key>  
          <index column="type"></index>  
          <one-to-many class="Fight"/>  
 </list>  
</class>

检索现有事件

    public Event getEvtByDateAddress(String _date, String _address)
{
    try
    {
        if(!session.isOpen())
        {
            session = HibernateUtil.getSessionFactory().openSession();
        }
        session.beginTransaction();
        Criteria criteria = session.createCriteria(Event.class);
        criteria.add(Restrictions.eq("date", _date));
        criteria.add(Restrictions.eq("address", _address));
        Event evt = (Event)criteria.uniqueResult();
        if (evt==null)
        {
            return null;
        }
        else
        {
            return evt;
        }
    }
    catch(Exception e)
    {
        return null;
    }
}

调用此更新。

    public int updateEvent(Event _event)
{
    try
    {
        if(!session.isOpen())
        {
            session = HibernateUtil.getSessionFactory().openSession();
        }
        Event tmpEvent=new Event();
        if((tmpEvent=this.getEvtByDateAddress(_event.getDate(), _event.getAddress()))!=null)
        {
            tmpEvent.setFights(_event.getFights());
            Transaction tx =session.beginTransaction();
            session.update(tmpEvent);
            session.flush();
            tx.commit();
            session.close();
            return 0;
        }
        else
        {
            return -1;
        }
    }
    catch(Exception e){
        return -254;
    }
}

更新后,结果意外。插入新记录而不是更新记录。

oid boxer1Oid   boxer2Oid   eventOid    type
  1         1           3         \N    \N
  2         2           4         \N    \N
  3         5           6         \N    \N
  4         7           8         \N    \N
  5         1           2          1    0
  6         3           4          1    1
  7         5           6          1    2
  8         7           8          1    3

预期结果

oid boxer1Oid   boxer2Oid   eventOid    type
  1         1           2          1     0
  2         3           4          1     1
  3         5           6          1     2
  4         7           8          1     3

我只是检索现有记录并对其进行修改,结果出乎意料。

if((tmpEvent=this.getEvtByDateAddress(_event.getDate(),_event.getAddress()))!=null)

            tmpEvent.setFights(_event.getFights());
            -------
            session.update(tmpEvent);

我错过了什么才能获得预期的结果?

谢谢

1 个答案:

答案 0 :(得分:1)

确保this.getEvtByDateAddress设置oid返回的实体的getFights

此外,请勿创建新事件。 Event tmpEvent=new Event();可以是Event tmpEvent = null;