1、整合Mybatis
因为业务需求,springboot 整合一下通用Mapper
1、引入依赖
引入Mybatis和通用mapper依赖
<dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-jdbc</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- https://mvnrepository.com/artifact/tk.mybatis/mapper-spring-boot-starter --><dependency><groupId>tk.mybatis</groupId><artifactId>mapper-spring-boot-starter</artifactId><version>2.1.5</version></dependency>
2、SQL语句
DROPTABLEIFEXISTS`user`;CREATETABLE`user`(`id`int(0)NOTNULLAUTO_INCREMENT,`user_name`varchar(32)CHARACTERSET utf8COLLATE utf8_general_ciNOTNULL,`pass_word`varchar(50)CHARACTERSET utf8COLLATE utf8_general_ciNOTNULL,`real_name`varchar(32)CHARACTERSET utf8COLLATE utf8_general_ciNULLDEFAULTNULL,`update_time`datetime(0)NULLDEFAULTNULL,PRIMARYKEY(`id`)USINGBTREE)ENGINE=InnoDBAUTO_INCREMENT=3CHARACTERSET= utf8COLLATE= utf8_general_ci ROW_FORMAT= Dynamic;SET FOREIGN_KEY_CHECKS=1;
3、注解类
create_time也是同理
/**
* 每次update会自动更新时间
*/@Retention(value=RetentionPolicy.RUNTIME)@Target(value=ElementType.FIELD)public@interfaceUpdateTime{Stringvalue()default"";}
4、实体类字段
privateInteger id;privateString userName;privateString passWord;privateString realName;@UpdateTimeprivateDate updateTime;
5、拦截器的编写
我们写一个拦截器,当我们每次执行修改/新增的时候,我们自动的给update_time字段附上最新的时间值。不需要每次都手动赋值。
/**
* Mybatis update 拦截器
* @author 北堂飘霜
*/@Component@Intercepts({@Signature(type=Executor.class,method="update",args={MappedStatement.class,Object.class})})publicclassMybatisInterceptorimplementsInterceptor{/**
* 正则匹配 insert、delete、update操作
*/privatestaticfinalString REGEX=".*insert\\\\u0020.*|.*delete\\\\u0020.*|.*update\\\\u0020.*";@OverridepublicObjectintercept(Invocation invocation)throwsThrowable{User user=(User) invocation.getArgs()[1];Field[] fields= user.getClass().getDeclaredFields();for(Field field: fields){UpdateTime annotation= field.getAnnotation(UpdateTime.class);if(annotation!=null){// 设置 值
field.setAccessible(true);
field.set(user,newDate());}}return invocation.proceed();}@OverridepublicObjectplugin(Object o){//获取代理权if(oinstanceofExecutor){//如果是Executor(执行增删改查操作),则拦截下来returnPlugin.wrap(o,this);}else{return o;}}@OverridepublicvoidsetProperties(Properties properties){//读取mybatis配置文件中属性}}
6、service层和mapper层的编写
@ServicepublicclassUserServiceImplimplementsUserService{@AutowiredprivateUserMapper userMapper;@OverridepublicList<User>selectAll(){System.out.println(userMapper);return userMapper.selectAll();}@OverridepublicUsergetById(String id){return userMapper.selectByPrimaryKey(id);}@OverridepublicStringupdate(User user){
userMapper.insert(user);return"ok";}}
mapper需要继承通用mapper的mapper
publicinterfaceUserMapperextendsMapper<User>{}
7、注意事项
完成了以上操作,如果启动会报错,我们需要指定mapper的扫描路径的。
@SpringBootApplication@MapperScan("com.xxx.xxx.dao")publicclassMabatisInterceptorApplication{publicstaticvoidmain(String[] args){SpringApplication.run(MabatisInterceptorApplication.class, args);}}
2、寄语
1、用途概述
完成以上代码,每次我们去update/insert的时候,可以把时间自动加上去,当然了,因为需求就是加上最新的时间,所以对注解没怎么处理。事实上可以给注解赋值,甚至可以详细到加到秒,例如:
@UpdateTime(value="now()")// 当前时间@UpdateTime(value="pre()")// 前一天零点@UpdateTime(value="next()")// 后一天零点@UpdateTime(value="yyyy-MM-DD hh:mm:ss")// 任意时间@UpdateTime(value="noop")// 不做任何处理
这些如果有兴趣,也可以实现更加细粒度的控制,这个业务算是抛砖引玉了。