0

这是我需要的示例:

public class UserTransactionManager implements PreInsertEventListener, PreUpdateEventListener,
    ApplicationContextAware {

private static final long  serialVersionUID = -3535037001167635519L;
private static Log         log              = LogFactory.getLog(UserTransactionManager.class);

private ApplicationContext context;

@Override
public boolean onPreUpdate(PreUpdateEvent event) {
    if (event.getEntity() instanceof UserTransaction) {
        try {
            UserTransaction transaction = (UserTransaction) event.getEntity();
            log.debug("Pre update transaction action: " + transaction.getId());
            Integer index = Arrays.asList(event.getPersister().getPropertyNames()).indexOf(
                    "payed");
            if (!(Boolean) event.getOldState()[index] && (Boolean) event.getState()[index]) {
                AppUser user = (AppUser) event.getSession().load(AppUser.class,
                        transaction.getUser().getId());
                if (transaction.getType() == TransactionType.INCOMING) {
                    user.setBalance(user.getBalance() + transaction.getValue());
                } else {
                    user.setBalance(user.getBalance() - transaction.getValue());
                }
                transaction.setBalance(user.getBalance());
                event.getSession().update(user);
            } else if ((Boolean) event.getOldState()[index]
                    && !(Boolean) event.getState()[index]) {
                AppUser user = (AppUser) event.getSession().load(AppUser.class,
                        transaction.getUser().getId());
                if (transaction.getType() == TransactionType.INCOMING) {
                    user.setBalance(user.getBalance() - transaction.getValue());
                } else {
                    user.setBalance(user.getBalance() + transaction.getValue());
                }
                transaction.setBalance(user.getBalance());
                event.getSession().update(user);
            }
        } catch (Throwable ex) {
            return true;
        }
    }
    return false;
}

所以,事件被执行,但我不知道如何从这个 list3ner 中更新用户实体。 event.getSession().update(user);不工作

有什么办法吗?

Spring 正在管理我的数据库会话。

Spring - 3.1.0.RELEASE Hibernate - 3.5.6-Final

4

1 回答 1

0

不要在侦听器中保存或更新对象,这不是必需的。侦听器的意图是您允许在保存之前修改实体对象。因此休眠会话将处理模型中存在的更改,这意味着您可以自由修改对象字段。

请确保返回类型为真。请参阅参考 http://docs.jboss.org/hibernate/orm/3.6/javadocs/org/hibernate/event/PreInsertEventListener.html

    if (event.getEntity() instanceof UserTransaction) {

       try{

           ----------------
           -------------
            return true;
        } catch (Throwable ex) {
             return false; // you already got exception so not required the partial changes in your entity. 
      }
于 2013-08-14T14:40:55.120 回答