springboot~mybatis统一处理公有字段
对于实体中包含有公共字段,像create_at,create_time,update_at,update_time来说,我们没有必要在每个实体的crud操作中复制同样的代码,这样代码的味道很坏,我们应该使用mybatis的拦截器机制,将公共字段统一处理;当然mybatis-puls在实现上更加优雅,它帮我们封装了MetaObjectHandler
接口,我们可以重写insertFill
和updateFill
来完成公共字段的统一填充,详细可看我这篇文章《springboot~MyBatisPlus中使用@TableField完成字段自动填充》。
mybatis中的实现
-
需要实现org.apache.ibatis.plugin.Interceptor接口
-
在intercept方法中实现业务核心逻辑
-
在SqlSessionFactory中注册你的intercept类
-
拦截器代码
@Intercepts({ @Signature(type = Executor.class, method = "update", args = { MappedStatement.class, Object.class }) })
public class FillCreateAndUpdateFieldInterceptor implements Interceptor {
static final Logger logger = LoggerFactory.getLogger(FillCreateAndUpdateFieldInterceptor.class);
@Override
public Object intercept(Invocation invocation) throws Throwable {
Object[] args = invocation.getArgs();
MappedStatement ms = (MappedStatement) args[0];
Object parameter = args[1];
if (ms.getId().contains("insert") || ms.getId().contains("update")) {
if (SecurityUtils.getAuthentication() != null) {
if (parameter instanceof BaseEntity) {
BaseEntity entity = (BaseEntity) parameter;
if (ms.getId().contains("insert")) {
entity.setCreateBy(SecurityUtils.getAuthentication().getName());
entity.setCreateTime(new Date());
}
entity.setUpdateBy(SecurityUtils.getAuthentication().getName());
entity.setUpdateTime(new Date());
}
}
}
}
- 自定义SqlSessionFactory的bean
@Bean
public SqlSessionFactory sqlSessionFactory(DataSource dataSource) throws Exception {
String typeAliasesPackage = env.getProperty("mybatis.typeAliasesPackage");
String mapperLocations = env.getProperty("mybatis.mapperLocations");
String configLocation = env.getProperty("mybatis.configLocation");
typeAliasesPackage = setTypeAliasesPackage(typeAliasesPackage);
VFS.addImplClass(SpringBootVFS.class);
final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
sessionFactory.setTypeAliasesPackage(typeAliasesPackage);
sessionFactory.setMapperLocations(resolveMapperLocations(StringUtils.split(mapperLocations, ",")));
sessionFactory.setConfigLocation(new DefaultResourceLoader().getResource(configLocation));
SqlSessionFactory result = sessionFactory.getObject();
// 注册自定义拦截器
result.getConfiguration().addInterceptor(new FillCreateAndUpdateFieldInterceptor());
return result;
}
通过上面的代码,我们就完成了公共字段的统一处理。