PreInsert and PreUpdate Event Listener in hibernate

前端 未结 3 1860
有刺的猬
有刺的猬 2021-02-06 18:04

I have used PreInsertEventListener and PreUpdateEventListener Event Listener to insert created date and updated date in table.
The problem i am fac

3条回答
  •  渐次进展
    2021-02-06 18:46

    I had created Interceptor extend it with Hibernate EmptyInterceptor.
    Override method onSave() which will be Called when you save an object, the object is not save into database yet and onFlushDirty() Called when you update an object, the object is not update into database yet.
    In this function i have check my method by its name in which i have to set date at the time of created or updated.
    Here is sample code of onFlushDirty() method.

    public boolean onFlushDirty(Object entity,Serializable id,Object[] currentState, 
                      Object[] previousState,String[] propertyNames, Type[] types) 
    {
    
        if ( entity instanceof City ) {
    
            for ( int i=0; i < propertyNames.length; i++ ) {
                if ( "lastUpdatedOn".equals( propertyNames[i] ) ) {
                    currentState[i] = new Date();
                    return true;
                }
            }
        }
        return false;
    }  
    

    Here lastUpdatedOn is my method name which set updated date of record.

    onSave() method :

    public boolean onSave(Object entity, Serializable id, Object[] state,   
                         String[] propertyNames, Type[] types)   
    {
        if ( entity instanceof City) {
    
            for ( int i=0; i

    Here createdOn is method to set created date for record.

    Extend your POJO class with this interceptor class.

提交回复
热议问题