我正在使用MyBatis并希望在每个“创建”,“修改”的表上实现2个字段。它们都是日期字段。有没有办法在插入或更新时自动更新这些字段?当然,我可以调整映射,但我想知道是否有更通用和干燥的方式来做这个?
答案 0 :(得分:7)
不,如果没有编写sql映射来更新列,mybatis没有自动执行此操作的机制。
一种替代方案是database triggers。我不确定我会建议,但我们只是在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>
答案 1 :(得分:0)
您可以使用mybatis拦截器
这是我的示例(使用springboot):
在mycase中,BaseEntity是所有实体的超类,我需要在mybatis更新或插入数据库之前做一些事情。
步骤1:在BaseEntity中创建初始化方法以进行更新或插入
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
例如:道
@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);