@SuppressWarnings("unchecked")
 public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
   Object entity = event.getObject();
   boolean newEntity = !event.getSession().contains(entity);
   if (newEntity) {
     if (beforeInsertCaller != null) {
       beforeInsertCaller.call(entity);
       if (event.getSession().contains(entity)) {
         EntityEntry entry = event.getEntry();
         if (entry != null) {
           Object[] state = entry.getLoadedState();
           synchronizePersisterState(entity, entry.getPersister(), state);
         }
       }
     }
     if (shouldTimestamp) {
       long time = System.currentTimeMillis();
       if (dateCreatedProperty != null && newEntity) {
         Object now =
             DefaultGroovyMethods.newInstance(dateCreatedProperty.getType(), new Object[] {time});
         dateCreatedProperty.setProperty(entity, now);
       }
       if (lastUpdatedProperty != null) {
         Object now =
             DefaultGroovyMethods.newInstance(lastUpdatedProperty.getType(), new Object[] {time});
         lastUpdatedProperty.setProperty(entity, now);
       }
     }
   }
 }
  protected Serializable performSaveOrUpdate(SaveOrUpdateEvent event) {
    int entityState =
        getEntityState(
            event.getEntity(), event.getEntityName(), event.getEntry(), event.getSession());

    switch (entityState) {
      case DETACHED:
        entityIsDetached(event);
        return null;
      case PERSISTENT:
        return entityIsPersistent(event);
      default: // TRANSIENT or DELETED
        return entityIsTransient(event);
    }
  }
  protected Serializable entityIsPersistent(SaveOrUpdateEvent event) throws HibernateException {
    LOG.trace("Ignoring persistent instance");

    EntityEntry entityEntry = event.getEntry();
    if (entityEntry == null) {
      throw new AssertionFailure("entity was transient or detached");
    } else {

      if (entityEntry.getStatus() == Status.DELETED) {
        throw new AssertionFailure("entity was deleted");
      }

      final SessionFactoryImplementor factory = event.getSession().getFactory();

      Serializable requestedId = event.getRequestedId();

      Serializable savedId;
      if (requestedId == null) {
        savedId = entityEntry.getId();
      } else {

        final boolean isEqual =
            !entityEntry
                .getPersister()
                .getIdentifierType()
                .isEqual(
                    requestedId, entityEntry.getId(), event.getSession().getEntityMode(), factory);

        if (isEqual) {
          throw new PersistentObjectException(
              "object passed to save() was already persistent: "
                  + MessageHelper.infoString(entityEntry.getPersister(), requestedId, factory));
        }

        savedId = requestedId;
      }

      if (LOG.isTraceEnabled())
        LOG.trace(
            "Object already associated with session: "
                + MessageHelper.infoString(entityEntry.getPersister(), savedId, factory));

      return savedId;
    }
  }
  public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
    Object object = event.getObject();

    // 如果对象是AuditableEntity子类,添加审计信息.
    if (object instanceof AuditableEntity) {
      AuditableEntity entity = (AuditableEntity) object;
      // String loginName = SpringSecurityUtils.getCurrentUserName();
      String loginName = "系统定义";

      AccountManager manager = (AccountManager) SpringContextHolder.getBean("accountManager");

      if (entity.getId() == null) {
        // 创建新对象
        entity.setCreateTime(manager.getNowString());

        if (entity.getCreateBy() == null) {
          HttpServletRequest request =
              ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
          UserSession u = (UserSession) request.getSession().getAttribute("userSession");
          if (u != null) {
            loginName = u.getAccount().getUserName();
          }
          entity.setCreateBy(loginName);
        }
      } else {
        // 修改旧对象
        entity.setLastModifyTime(manager.getNowString());

        if (entity.getLastModifyBy() == null) {
          HttpServletRequest request =
              ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
          UserSession u = (UserSession) request.getSession().getAttribute("userSession");
          if (u != null) {
            loginName = u.getAccount().getUserName();
          }
          entity.setLastModifyBy(loginName);
        }

        logger.info(
            "{}对象(ID:{}) 被 {} 在 {} 修改",
            new Object[] {event.getEntityName(), entity.getId(), loginName, new Date()});
      }
    }
  }
 @Override
 public void onSaveOrUpdate(SaveOrUpdateEvent event) {
   if (event.getObject() instanceof PersistentEntity) {
     PersistentEntity persistentEntity = (PersistentEntity) event.getObject();
     Date updated = new Date();
     persistentEntity.setUpdated(updated);
     if (event.getObject() instanceof CatalogNode) {
       CatalogNode catalogNode = (CatalogNode) event.getObject();
       if (catalogNode.getParent() != null) {
         String parentNumericPath = catalogNode.getParent().getId() + ".";
         if (catalogNode.getParent().getParentNumericPath() != null) {
           parentNumericPath = catalogNode.getParent().getParentNumericPath() + parentNumericPath;
         }
         catalogNode.setParentNumericPath(parentNumericPath);
       }
     }
   }
   super.onSaveOrUpdate(event);
 }
 /**
  * Handles the calls needed to perform cascades as part of an update request for the given entity.
  *
  * @param event The event currently being processed.
  * @param persister The defined persister for the entity being updated.
  * @param entity The entity being updated.
  */
 private void cascadeOnUpdate(SaveOrUpdateEvent event, EntityPersister persister, Object entity) {
   EventSource source = event.getSession();
   source.getPersistenceContext().incrementCascadeLevel();
   try {
     new Cascade(CascadingAction.SAVE_UPDATE, Cascade.AFTER_UPDATE, source)
         .cascade(persister, entity);
   } finally {
     source.getPersistenceContext().decrementCascadeLevel();
   }
 }
  /**
   * The given save-update event named a transient entity.
   *
   * <p>Here, we will perform the save processing.
   *
   * @param event The save event to be handled.
   * @return The entity's identifier after saving.
   */
  protected Serializable entityIsTransient(SaveOrUpdateEvent event) {

    LOG.trace("Saving transient instance");

    final EventSource source = event.getSession();

    EntityEntry entityEntry = event.getEntry();
    if (entityEntry != null) {
      if (entityEntry.getStatus() == Status.DELETED) {
        source.forceFlush(entityEntry);
      } else {
        throw new AssertionFailure("entity was persistent");
      }
    }

    Serializable id = saveWithGeneratedOrRequestedId(event);

    source.getPersistenceContext().reassociateProxy(event.getObject(), id);

    return id;
  }
  /**
   * Handle the given update event.
   *
   * @param event The update event to be handled.
   */
  public void onSaveOrUpdate(SaveOrUpdateEvent event) {
    final SessionImplementor source = event.getSession();
    final Object object = event.getObject();
    final Serializable requestedId = event.getRequestedId();

    if (requestedId != null) {
      // assign the requested id to the proxy, *before*
      // reassociating the proxy
      if (object instanceof HibernateProxy) {
        ((HibernateProxy) object).getHibernateLazyInitializer().setIdentifier(requestedId);
      }
    }

    // For an uninitialized proxy, noop, don't even need to return an id, since it is never a save()
    if (reassociateIfUninitializedProxy(object, source))
      LOG.trace("Reassociated uninitialized proxy");
    else {
      // initialize properties of the event:
      final Object entity = source.getPersistenceContext().unproxyAndReassociate(object);
      event.setEntity(entity);
      event.setEntry(source.getPersistenceContext().getEntry(entity));
      // return the id in the event object
      event.setResultId(performSaveOrUpdate(event));
    }
  }
  /**
   * The given save-update event named a detached entity.
   *
   * <p>Here, we will perform the update processing.
   *
   * @param event The update event to be handled.
   */
  protected void entityIsDetached(SaveOrUpdateEvent event) {

    LOG.trace("Updating detached instance");

    if (event.getSession().getPersistenceContext().isEntryFor(event.getEntity())) {
      // TODO: assertion only, could be optimized away
      throw new AssertionFailure("entity was persistent");
    }

    Object entity = event.getEntity();

    EntityPersister persister =
        event.getSession().getEntityPersister(event.getEntityName(), entity);

    event.setRequestedId(
        getUpdateId(entity, persister, event.getRequestedId(), event.getSession()));

    performUpdate(event, entity, persister);
  }
Esempio n. 10
0
 @Override
 public void onSaveOrUpdate(SaveOrUpdateEvent event) {
   Object object = event.getObject();
   if (object instanceof AuditSaveEntity || object instanceof AuditUpdateEntity) {
     Serializable id = ((AuditSaveEntity) object).getId();
     String loginName = SpringSecurityUtils.getCurrentUserName();
     if (id == null) {
       if (object instanceof AuditSaveEntity) {
         AuditSaveEntity auditObject = (AuditableEntity) object;
         auditObject.setCreateBy(loginName);
         auditObject.setCreateTime(new Date());
       }
     } else {
       if (object instanceof AuditUpdateEntity) {
         AuditUpdateEntity auditObject = (AuditableEntity) object;
         auditObject.setUpdateBy(loginName);
         auditObject.setUpdateTime(new Date());
       }
     }
   }
   super.onSaveOrUpdate(event);
 }
  protected void performUpdate(SaveOrUpdateEvent event, Object entity, EntityPersister persister)
      throws HibernateException {

    if (!persister.isMutable()) LOG.trace("Immutable instance passed to performUpdate()");

    if (LOG.isTraceEnabled())
      LOG.trace(
          "Updating "
              + MessageHelper.infoString(
                  persister, event.getRequestedId(), event.getSession().getFactory()));

    final EventSource source = event.getSession();
    final EntityKey key = source.generateEntityKey(event.getRequestedId(), persister);

    source.getPersistenceContext().checkUniqueness(key, entity);

    if (invokeUpdateLifecycle(entity, persister, source)) {
      reassociate(event, event.getObject(), event.getRequestedId(), persister);
      return;
    }

    // this is a transient object with existing persistent state not loaded by the session

    new OnUpdateVisitor(source, event.getRequestedId(), entity).process(entity, persister);

    // TODO: put this stuff back in to read snapshot from
    // the second-level cache (needs some extra work)
    /*Object[] cachedState = null;

    if ( persister.hasCache() ) {
    	CacheEntry entry = (CacheEntry) persister.getCache()
    			.get( event.getRequestedId(), source.getTimestamp() );
        cachedState = entry==null ?
        		null :
        		entry.getState(); //TODO: half-assemble this stuff
    }*/

    source
        .getPersistenceContext()
        .addEntity(
            entity,
            (persister.isMutable() ? Status.MANAGED : Status.READ_ONLY),
            null, // cachedState,
            key,
            persister.getVersion(entity, source.getEntityMode()),
            LockMode.NONE,
            true,
            persister,
            false,
            true // assume true, since we don't really know, and it doesn't matter
            );

    persister.afterReassociate(entity, source);

    if (LOG.isTraceEnabled())
      LOG.trace(
          "Updating "
              + MessageHelper.infoString(persister, event.getRequestedId(), source.getFactory()));

    cascadeOnUpdate(event, persister, entity);
  }
 /**
  * Save the transient instance, assigning the right identifier
  *
  * @param event The initiating event.
  * @return The entity's identifier value after saving.
  */
 protected Serializable saveWithGeneratedOrRequestedId(SaveOrUpdateEvent event) {
   return saveWithGeneratedId(
       event.getEntity(), event.getEntityName(), null, event.getSession(), true);
 }