数据库自动更新创建时间、更新时间字段,免去mybatis的设置

 ALTER TABLE test MODIFY create_time timestamp not null default CURRENT_TIMESTAMP COMMENT '创建时间';


 ALTER TABLE test   MODIFY update_time timestamp not null default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP COMMENT '更新时间';

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以通过在实体类中添加两个字段来实现自动更新创建时间更新时间。例如,在实体类中添加一个名为"createTime"的Date类型字段和一个名为"updateTime"的Date类型字段,并在对应的getter方法中实现自动更新时间的逻辑。 在MyBatis中,可以通过使用拦截器的方式来实现自动更新时间。具体操作如下: 1. 创建一个拦截器类,实现Interceptor接口,重写intercept方法,在该方法中实现自动更新时间的逻辑。 2. 在MyBatis的配置文件中配置拦截器,将拦截器添加到插件列表中。 3. 在Mapper.xml文件中,将需要自动更新时间字段配置为#{createTime,jdbcType=TIMESTAMP}和#{updateTime,jdbcType=TIMESTAMP},MyBatis自动将Java对象中的时间字段转换为数据库中的时间类型。 示例代码如下: 实体类: ```java public class User { private Long id; private String name; private Date createTime; private Date updateTime; // getter and setter // ... } ``` 拦截器实现: ```java @Intercepts({ @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}) }) public class TimeInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { Object[] args = invocation.getArgs(); MappedStatement ms = (MappedStatement) args[0]; Object parameter = args[1]; SqlCommandType sqlCommandType = ms.getSqlCommandType(); if (parameter instanceof User) { User user = (User) parameter; Date now = new Date(); if (SqlCommandType.INSERT.equals(sqlCommandType)) { user.setCreateTime(now); user.setUpdateTime(now); } else if (SqlCommandType.UPDATE.equals(sqlCommandType)) { user.setUpdateTime(now); } } return invocation.proceed(); } @Override public Object plugin(Object target) { return Plugin.wrap(target, this); } @Override public void setProperties(Properties properties) { // do nothing } } ``` MyBatis配置文件: ```xml <configuration> <plugins> <plugin interceptor="com.example.TimeInterceptor" /> </plugins> <!-- other configurations --> </configuration> ``` Mapper.xml文件: ```xml <insert id="insert" parameterType="User"> INSERT INTO user (name, create_time, update_time) VALUES ( #{name, jdbcType=VARCHAR}, #{createTime, jdbcType=TIMESTAMP}, #{updateTime, jdbcType=TIMESTAMP} ) </insert> <update id="update" parameterType="User"> UPDATE user SET name = #{name, jdbcType=VARCHAR}, update_time = #{updateTime, jdbcType=TIMESTAMP} WHERE id = #{id, jdbcType=BIGINT} </update> ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值