使用MyBatis时如何自动更新创建/修改日期等字段?

发布于 2024-12-01 12:05:38 字数 114 浏览 1 评论 0原文

我正在使用 MyBatis,并希望在“创建”、“修改”的每个表上实现 2 个字段。它们都是日期字段。有没有办法在插入或更新时自动更新这些字段?当然,我可以调整映射,但我想知道是否有更通用和更干燥的方法来做到这一点?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

七色彩虹 2024-12-08 12:05:38

不,mybatis 没有机制可以自动执行此操作,无需您编写 sql 映射来更新列。

一种替代方法是数据库触发器。但我不确定我是否会建议这样做,我们只是在 sql 映射中对其进行编码。

您可以像这样在 SQL 映射中对其进行编码,

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

或者,

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

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>
撩人痒 2024-12-08 12:05:38

你可以使用mybatis拦截器
这是我的示例(使用 springboot):
就我而言,BaseEntity是所有实体的超类,我需要在mybatis更新或插入数据库之前做一些事情。
第1步:在BaseEntity中创建init方法用于更新或插入

public class BaseEntity{
    private Date created;
    private Date updated;

    //getter,setter
    public void initCreateEntity() {  
        this.created = new Date()
        this.updated = new Date()
    }

    public void initUpdateEntity() {  
        this.created = new Date()
        this.updated = new Date()
    }
  }  

第2步:添加mybatis拦截器

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

    /**
     * add time interceptor for update
     */
    @Intercepts(@Signature(type = Executor.class, method = "update", args={MappedStatement.class, Object.class}))
    public class BaseEntityInterceptor implements Interceptor {
        @Override
        public Object intercept(Invocation invocation) throws Throwable {
            MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
            // get sql
            SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
            // get parameter , this is the target object that you want to handle
            Object parameter = invocation.getArgs()[1];
            // make sure super class is BaseEntity 
            if (parameter instanceof BaseEntity) {
                //init 
                BaseEntity baseEntity = (BaseEntity) parameter;
                if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                    baseEntity.initCreateEntity();
                } else if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
                    baseEntity.initUpdateEntity();
                }
            }
    
            return invocation.proceed();
       }
    
        @Override
        public Object plugin(Object o) {
            return Plugin.wrap(o, this);
        }
    
        @Override
        public void setProperties(Properties properties) {
    
        }
      }

第3步:添加到springboot配置中的bean上下文

@Configuration
public class MyBatisConfig {

    @Bean
    public BaseEntityInterceptor baseEntityInterceptor() {
        return new BaseEntityInterceptor();
    }
}

第 4 步:Dao 和 Mapper.xml

//base update or insert sql incloude column created and updated

例如:Dao

@Mapper
   public interface BaseDao {
      int update(BaseEntity baseEntity);
   }

Mapper.xml

    <update id="update" parameterType="com.package.to.BaseEntity">
        update baseentity_table set created = #{createTime, jdbcType=TIMESTAMP}
updated = #{createTime, jdbcType=TIMESTAMP} 
    </update>

第 5 步:测试

   baseDao.update(new BaseEntity);

更多信息:https://mybatis.org/mybatis-3/configuration.html#plugins

you can use mybatis Interceptor
here is my example (using springboot):
in mycase, BaseEntity is the super class of all entity,i need do some thing before update or insert to database by mybatis.
step 1: create init method in BaseEntity for update or insert

public class BaseEntity{
    private Date created;
    private Date updated;

    //getter,setter
    public void initCreateEntity() {  
        this.created = new Date()
        this.updated = new Date()
    }

    public void initUpdateEntity() {  
        this.created = new Date()
        this.updated = new Date()
    }
  }  

step 2: add a mybatis interceptor

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;

    /**
     * add time interceptor for update
     */
    @Intercepts(@Signature(type = Executor.class, method = "update", args={MappedStatement.class, Object.class}))
    public class BaseEntityInterceptor implements Interceptor {
        @Override
        public Object intercept(Invocation invocation) throws Throwable {
            MappedStatement mappedStatement = (MappedStatement)invocation.getArgs()[0];
            // get sql
            SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
            // get parameter , this is the target object that you want to handle
            Object parameter = invocation.getArgs()[1];
            // make sure super class is BaseEntity 
            if (parameter instanceof BaseEntity) {
                //init 
                BaseEntity baseEntity = (BaseEntity) parameter;
                if (SqlCommandType.INSERT.equals(sqlCommandType)) {
                    baseEntity.initCreateEntity();
                } else if (SqlCommandType.UPDATE.equals(sqlCommandType)) {
                    baseEntity.initUpdateEntity();
                }
            }
    
            return invocation.proceed();
       }
    
        @Override
        public Object plugin(Object o) {
            return Plugin.wrap(o, this);
        }
    
        @Override
        public void setProperties(Properties properties) {
    
        }
      }

step 3: add to bean Context in springboot config

@Configuration
public class MyBatisConfig {

    @Bean
    public BaseEntityInterceptor baseEntityInterceptor() {
        return new BaseEntityInterceptor();
    }
}

step 4: Dao and Mapper.xml

//base update or insert sql incloude column created and updated

eg:Dao

@Mapper
   public interface BaseDao {
      int update(BaseEntity baseEntity);
   }

Mapper.xml

    <update id="update" parameterType="com.package.to.BaseEntity">
        update baseentity_table set created = #{createTime, jdbcType=TIMESTAMP}
updated = #{createTime, jdbcType=TIMESTAMP} 
    </update>

step 5: test

   baseDao.update(new BaseEntity);

More information here: https://mybatis.org/mybatis-3/configuration.html#plugins

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文