import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.util.Date;
@Component
@Configuration
public class MetaObjectHandlerConfig implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
// 获取当前时间
Date dateTime = new Date();
if (metaObject.hasGetter("createdAt")) {
setFieldValByName("createdAt", dateTime, metaObject);
}
if (metaObject.hasGetter("updatedAt")) {
setFieldValByName("updatedAt", dateTime, metaObject);
}
}
@Override
public void updateFill(MetaObject metaObject) {
if (metaObject.hasGetter("updatedAt")) {
Date dateTime = new Date();
setFieldValByName("updatedAt", dateTime, metaObject);
}
}
}
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
@Configuration
//@MapperScan("com.admin.mapper*")//这个注解,作用相当于下面的@Bean MapperScannerConfigurer,2者配置1份即可
public class MybatisPlusConfig {
@Autowired
private DataSource dataSource;
@Bean
public MybatisPlusInterceptor optimisticLockerInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 配置分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
// 配置乐观锁
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
return interceptor;
}
@Bean
public String myInterceptor(SqlSessionFactory sqlSessionFactory) {
//实例化插件
//将插件添加到SqlSessionFactory工厂
// sqlSessionFactory.getConfiguration().addInterceptor((Interceptor) dataSource);
// sqlSessionFactory.getConfiguration().addInterceptor(sqlStatementInterceptor);
return "interceptor";
}
}