只有在任何eniy数据发生变化时才设置更新

时间:2016-01-14 16:08:00

标签: java hibernate jpa

在我的客户实体中,我想保存changedByUserId字段。如果客户的其他任何一个领域真的发生变化,我只想设置此字段。如果我总是设置它,我强制EntityManager更新customer表,因为我设置了changedByUserId字段。

@Entity
@Table....
public class Customer {
    @Id
    private Long cusID;
    @Column
    private String cusNAME;
    @Column
    private Date changed;
    @Column
    private Long changedByUserId;

    @PreUpdate
    private preUpdate() {
        changed = new Date();
        // cannot set changedbyUserId here because no entitymanager 
        // available where i can query the id
    }
}

有人知道如何告诉EntityManager不检查changedByUserID字段中的更改吗?

1 个答案:

答案 0 :(得分:0)

您可以创建一个扩展org.hibernate.EmptyInterceptor的Interceptor类,并覆盖其方法以实现您想要的效果。您可以从here了解更多相关信息。例如:

public boolean onFlushDirty(Object entity, Serializable id, Object[] currentState, 
            Object[] previousState, String[] propertyNames, Type[] types) throws CallbackException {
        if ( entity instanceof YourBaseEntityClass) {
            int updatedPropertyCount = 0;
            for ( int i=0; i < propertyNames.length; i++ ) {                
                if ("UPDATED_ON_PROPERTY".equals( propertyNames[i] ) ) {
                    currentState[i] = new Date();
                    updatedPropertyCount++;
                }
                if ("UPDATED_BY_PROPERTY".equals( propertyNames[i] ) ) {
                    currentState[i] = Context.getContextUserId();
                    updatedPropertyCount++;
                }
                //if the conditioon passes both the properties have been updated
                //break from the loop 
                if(updatedPropertyCount == UPDATE_TOTAL_COUNT){
                    return true;
                }
            }
            //even if either of them modified returned true after the end of the loop
            if(updatedPropertyCount >0){
                return true;
            }           
        }
        return false;
    }