Hibernate实体版本没有增加,但数据库版本字段是

时间:2016-01-28 14:41:47

标签: java hibernate entity version

我不知道如何处理以下事项:

  1. 我在客户端创建一个实体,将其发送到服务器,合并并调用saveOrUpdate。合并后的实体将返回给客户端;
  2. 然后在客户端上修改实体,发送到服务器并再次调用saveOrUpdate。该方法退出但实体未更新其version号码并将其发送到客户端。现在,实体的版本号与数据库不同步。 数据库中的实体version字段已正确更新;
  3. 该实体将从其父集合中删除,但由于equals()方法使用version字段,因此它失败并且不会删除该实体。或者我在再次更新实体时获得OptimisticLockException
  4. 这是Hibernate的正常行为吗?

    1. 如果没有,可能是什么造成的呢?
    2. 如果是,那么我必须手动更新每个修改过的实体的版本字段,然后再将其返回给客户端吗?
    3. 服务类

      public List<HtDayEntry> deleteHtDayEntry(String clientVersion,
              @Lazy HtDayEntry htDayEntryToDelete, List<HtDayEntry> modifiedHtDayEntries)
              throws ClientServerVersionMismatchException {
          compareClientServerVersion(clientVersion);
          htDayEntryToDelete = (HtDayEntry) htDayEntryDao.merge(htDayEntryToDelete);
          // START: remove from the other side of the relationships
          HtDay htDay = htDayEntryToDelete.getHtDay();
          htDay.getHtDayEntries().remove(htDayEntryToDelete);
          HtDayEntryType htDayEntryType = htDayEntryToDelete.getHtDayEntryType();
          htDayEntryType.getHtDayEntries().remove(htDayEntryToDelete);
          for (HtNote htNote : htDayEntryToDelete.getHtNotes()) {
              htNote.setHtDayEntry(null);
          }
          // END: remove from the other side of the relationships
          htDayEntryDao.delete(htDayEntryToDelete);
          if (isHtDayEmpty(htDay)) {
              htDayDao.delete(htDay);
          }
          if (modifiedHtDayEntries != null) {
              HtDayEntry modifiedHtDayEntry;
              ListIterator iterator = modifiedHtDayEntries.listIterator();
              while(iterator.hasNext()){
                  modifiedHtDayEntry = (HtDayEntry) iterator.next();
                  modifiedHtDayEntry = (HtDayEntry) htDayEntryDao.merge(modifiedHtDayEntry);
                  htDayEntryDao.saveOrUpdate(modifiedHtDayEntry);
                  // START: must manually update the version field, I have no idea why
                  modifiedHtDayEntry.setVersion(modifiedHtDayEntry.getVersion() + 1);
                  iterator.set(modifiedHtDayEntry); // Update the modifiedHtDayEntry in the iterator so that the new version number can be returned
                  // END: must manually update the version field, I have no idea why
              }
          }
          return modifiedHtDayEntries;
      }
      

      HtDayEntryDao

      public void saveOrUpdate(Object object) throws HibernateException {
          getSession().saveOrUpdate(object);
      }
      

      实体(超类中的方法)

      private long version;
      
      @Version
      @Column(name = "version")
      public Long getVersion() {
          return version;
      }
      
      public void setVersion(Long version) {
          this.version = version;
      }
      

0 个答案:

没有答案