hibernate eventlistener中的DML操作

时间:2013-08-14 13:50:52

标签: java spring hibernate event-listener dml

这是我需要的样本:

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正在管理我的数据库会话。

春天 - 3.1.0.RELEASE Hibernate - 3.5.6-最终

1 个答案:

答案 0 :(得分:0)

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

请确保返回类型为真。 参见参考文献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. 
      }