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); } }
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()}); } } }
/** * 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); }
/** * 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); }