mybatis自动更新创建时间更新时间
时间: 2023-08-13 07:03:23 浏览: 385
可以通过在实体类中添加两个字段来实现自动更新创建时间和更新时间。例如,在实体类中添加一个名为"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>
```