Search code examples
springaopdrymybatis

How automatically update fields like created/modified Date when using MyBatis?


I am using MyBatis and want to implement 2 fields on every table 'created', 'modified'. Both off them are date fields. Is there a way of automatically update these fields on an insert or update? Of course, I can adjust the mappings, but I was wondering if there is a more generic and DRY way of doing this?


Solution

  • No, mybatis has no mechanism to do this automatically without you coding your sql maps to update the columns.

    One alternative would be database triggers. I'm not certain I would recommend that though, we just code it in the sql maps.

    You could code it in the SQL maps like this,

    <insert id="someInsert">    
         insert into dummy_table    
         ( 
             SOME_COLUMN,
             CREATED_DT    
         )    
         values
        (
            #{someValue},
            sysdate    
         ) 
    </insert>
    

    or,

    <update id="someUpdate">
       update some_table
       set some_column = #{someValue}, modified=sysdate
       where some_id = #{someId}
    </update>