以前一直使用Mybatis-Plus
,说实话,我的仍是比较喜欢Mybatis-Plus
。java
ORM
框架用的比较多的就两个,JPA
和Mybatis
。听说国内用Mybatis
比较多,国外用JPA
比较多。mysql
而Mybatis-Plus
是在Mybatis
的基础上,增长了不少牛🍺的功能。sql
详细的能够去官网看:mybatis.plus/ 官网新域名也是牛🍺。反正用过的都说好。数据库
至于JPA
,虽然我的以为有点太死板,不过也有值得学习的地方。mybatis
很早之前,用Mybatis-Plus
的时候,有一个比较麻烦的问题,就是若是一组数据存在多张表中,这些表之间多是一对一,一对多或者多对一,那我要想所有查出来就要调好几个Mapper
的查询方法。代码行数一下就增长了不少。app
以前也看过Mybatis-Plus
的源码,想过如何使Mybatis-Plus
支持多表联接查询。但是发现难度不小。由于Mybatis-Plus
底层就只支持单表。框架
最近看到JPA
的@OneToOne
、@OneToMany
、@ManyToMany
这些注解,突然一个想法就在个人脑海里闪现出来,若是像JPA
那样使用注解的方式,是否是简单不少呢?分布式
事先声明,全是本身想的,没有看JPA
源码, 因此实现方式可能和JPA
不同。ide
可能有人不知道,其实Mybatis
也是支持拦截器的,既然如此,用拦截器处理注解就能够啦。性能
@Inherited @Documented @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface One2One { /** * 本类主键列名 */ String self() default "id"; /** * 本类主键在关联表中的列名 */ String as(); /** * 关联的 mapper */ Class<? extends BaseMapper> mapper(); }
说一下,假若有两张表,A
和B
是一对一的关系,A
表id
在B
表中是a_id
,用这样的方式关联的。 在A
的实体类中使用这个注解,self
就是id
,而as
就是a_id
,意思就是A
的id
做为a_id
来查询,而mapper
就是B
的Mapper
,下面是例子A
就是UserAccount
,B
就是UserAddress
。
@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value = "UserAccount对象", description = "用户相关") public class UserAccount extends Model<UserAccount> { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "id") @TableId(value = "id", type = IdType.AUTO) private Long id; @ApiModelProperty(value = "昵称") private String nickName; @TableField(exist = false) //把id的值 做为userId 在 UserAddressMapper中 查询 @One2One(self = "id", as = "user_id", mapper = UserAddressMapper.class) private UserAddress address; @Override protected Serializable pkVal() { return this.id; } }
这里再也不详细介绍拦截器了,以前也写了几篇关于Mybatis拦截器的,有兴趣的能够去看看。
@Intercepts({ @Signature(type = ResultSetHandler.class, method = "handleResultSets", args = {Statement.class}) }) @Slf4j public class One2OneInterceptor implements Interceptor { @Override public Object intercept(Invocation invocation) throws Throwable { Object result = invocation.proceed(); if (result == null) { return null; } if (result instanceof ArrayList) { ArrayList list = (ArrayList) result; for (Object o : list) { handleOne2OneAnnotation(o); } } else { handleOne2OneAnnotation(result); } return result; } @SneakyThrows private void handleOne2OneAnnotation(Object o) { Class<?> aClass = o.getClass(); Field[] fields = aClass.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); One2One one2One = field.getAnnotation(One2One.class); if (one2One != null) { String self = one2One.self(); Object value = MpExtraUtil.getValue(o, self); String as = one2One.as(); Class<? extends BaseMapper> mapper = one2One.mapper(); BaseMapper baseMapper = SpringBeanFactoryUtils.getApplicationContext().getBean(mapper); QueryWrapper<Object> eq = Condition.create().eq(as, value); Object one = baseMapper.selectOne(eq); field.set(o, one); } } } @Override public Object plugin(Object o) { return Plugin.wrap(o, this); } @Override public void setProperties(Properties properties) { } }
Mybatis
拦截器能够针对不一样的场景进行拦截,好比:
Executor
:拦截执行器的方法。ParameterHandler
:拦截参数的处理。ResultHandler
:拦截结果集的处理。StatementHandler
:拦截Sql语法构建的处理。这里是经过拦截结果集的方式,在返回的对象上查找这个注解,找到注解后,再根据注解的配置,自动去数据库查询,查到结果后把数据封装到返回的结果集中。这样就避免了本身去屡次调Mapper
的查询方法。
难点:虽然注解上标明了是什么Mapper
,但是在拦截器中取到的仍是BaseMapper
,而用BaseMapper
实在很差查询,我试了不少方法,不过还好Mybatis-Plus
支持使用Condition.create().eq(as, value);
拼接条件SQL
,而后可使用baseMapper.selectOne(eq);
去查询。
public class MpExtraUtil { @SneakyThrows public static Object getValue(Object o, String name) { Class<?> aClass = o.getClass(); Field[] fields = aClass.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); if (field.getName().equals(name)) { return field.get(o); } } throw new IllegalArgumentException("未查询到名称为:" + name + " 的字段"); } }
MpExtraUtil
就是使用反射的方式,获取id
的值。
再讲一个多对多的注解
@Inherited @Documented @Target({ElementType.FIELD}) @Retention(RetentionPolicy.RUNTIME) public @interface Many2Many { /** * 本类主键列名 */ String self() default "id"; /** * 本类主键在中间表的列名 */ String leftMid(); /** * 另外一个多方在中间表中的列名 */ String rightMid(); /** * 另外一个多方在本表中的列名 */ String origin(); /** * 关联的 mapper */ Class<? extends BaseMapper> midMapper(); /** * 关联的 mapper */ Class<? extends BaseMapper> mapper();
假设有A
、 A_B
,B
三张表,在A
的实体类中使用这个注解, self
就是A
表主键id
,leftMid
就是A
表的id
在中间表中的名字,也就是a_id
,而rightMid
是B
表主键在中间表的名字,就是b_id
, origin
就是B
表本身主键原来的名字,即id
,midMapper
是中间表的Mapper
,也就是A_B
对应的Mapper
,mapper
是B
表的Mapper
。
这个确实有点绕。
还有一个@One2Many
就不说了,和@One2One
同样,至于Many2One
,从另外一个角度看就是@One2One
。
CREATE TABLE `user_account` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id', `nick_name` varchar(40) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '昵称', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户相关'; CREATE TABLE `user_address` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '地址id', `user_id` bigint(20) DEFAULT NULL COMMENT '用户id', `address` varchar(200) DEFAULT NULL COMMENT '详细地址', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE `user_class` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '课程id', `class_name` varchar(20) DEFAULT NULL COMMENT '课程名称', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE `user_hobby` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '爱好id', `user_id` bigint(20) DEFAULT NULL COMMENT '用户id', `hobby` varchar(40) DEFAULT NULL COMMENT '爱好名字', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE `user_mid_class` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '中间表id', `user_id` bigint(20) DEFAULT NULL COMMENT '用户id', `class_id` bigint(20) DEFAULT NULL COMMENT '课程id', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
<dependency> <groupId>top.lww0511</groupId> <artifactId>mp-extra</artifactId> <version>1.0.1</version> </dependency>
@EnableMpExtra
由于通常项目都会配置本身的MybatisConfiguration
,我在这里配置后,打包,而后被引入,是没法生效的。
因此就想了一种折中的方法。
之前MybatisConfiguration
是经过new
出来的,如今经过MybatisExtraConfig.getMPConfig();
来获取,这样获取到的MybatisConfiguration
就已经添加好了拦截器。
完整Mybatis-Plus
配置类例子,注意第43行:
@Slf4j @Configuration @MapperScan(basePackages = "com.ler.demo.mapper", sqlSessionTemplateRef = "sqlSessionTemplate") public class MybatisConfig { private static final String BASE_PACKAGE = "com.ler.demo."; @Bean("dataSource") public DataSource dataSource() { try { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://localhost/mp-extra?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai"); dataSource.setUsername("root"); dataSource.setPassword("adminadmin"); dataSource.setInitialSize(1); dataSource.setMaxActive(20); dataSource.setMinIdle(1); dataSource.setMaxWait(60_000); dataSource.setPoolPreparedStatements(true); dataSource.setMaxPoolPreparedStatementPerConnectionSize(20); dataSource.setTimeBetweenEvictionRunsMillis(60_000); dataSource.setMinEvictableIdleTimeMillis(300_000); dataSource.setValidationQuery("SELECT 1"); return dataSource; } catch (Throwable throwable) { log.error("ex caught", throwable); throw new RuntimeException(); } } @Bean(name = "sqlSessionFactory") public SqlSessionFactory sqlSessionFactory(@Qualifier("dataSource") DataSource dataSource) throws Exception { MybatisSqlSessionFactoryBean factoryBean = new MybatisSqlSessionFactoryBean(); factoryBean.setDataSource(dataSource); factoryBean.setVfs(SpringBootVFS.class); factoryBean.setTypeAliasesPackage(BASE_PACKAGE + "entity"); Resource[] mapperResources = new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*.xml"); factoryBean.setMapperLocations(mapperResources); // 43行 获取配置 MybatisConfiguration configuration = MybatisExtraConfig.getMPConfig(); configuration.setDefaultScriptingLanguage(MybatisXMLLanguageDriver.class); configuration.setJdbcTypeForNull(JdbcType.NULL); configuration.setMapUnderscoreToCamelCase(true); configuration.addInterceptor(new SqlExplainInterceptor()); configuration.setUseGeneratedKeys(true); factoryBean.setConfiguration(configuration); return factoryBean.getObject(); } @Bean(name = "sqlSessionTemplate") public SqlSessionTemplate sqlSessionTemplate(@Qualifier("sqlSessionFactory") SqlSessionFactory sqlSessionFactory) { return new SqlSessionTemplate(sqlSessionFactory); } @Bean(name = "transactionManager") public PlatformTransactionManager platformTransactionManager(@Qualifier("dataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } @Bean(name = "transactionTemplate") public TransactionTemplate transactionTemplate(@Qualifier("transactionManager") PlatformTransactionManager transactionManager) { return new TransactionTemplate(transactionManager); } }
@Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value = "UserAccount对象", description = "用户相关") public class UserAccount extends Model<UserAccount> { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "id") @TableId(value = "id", type = IdType.AUTO) private Long id; @ApiModelProperty(value = "昵称") private String nickName; @TableField(exist = false) //把id的值 做为userId 在 UserAddressMapper中 查询 @One2One(self = "id", as = "user_id", mapper = UserAddressMapper.class) private UserAddress address; @TableField(exist = false) @One2Many(self = "id", as = "user_id", mapper = UserHobbyMapper.class) private List<UserHobby> hobbies; @TableField(exist = false) @Many2Many(self = "id", leftMid = "user_id", rightMid = "class_id", origin = "id" , midMapper = UserMidClassMapper.class, mapper = UserClassMapper.class) private List<UserClass> classes; @Override protected Serializable pkVal() { return this.id; } }
主要是那几个注解。对了还要加@TableField(exist = false)
,否则会报错。
源码:https://www.douban.com/note/7...
@Slf4j @RestController @RequestMapping("/user") @Api(value = "/user", description = "用户") public class UserAccountController { @Resource private UserAccountService userAccountService; @Resource private UserAccountMapper userAccountMapper; @ApiOperation("查询一个") @ApiImplicitParams({ @ApiImplicitParam(name = "", value = "", required = true), }) @GetMapping(value = "/one", name = "查询一个") public HttpResult one() { //service UserAccount account = userAccountService.getById(1L); //mapper // UserAccount account = userAccountMapper.selectById(1L); //AR模式 // UserAccount account = new UserAccount(); // account.setId(1L); // account = account.selectById(); return HttpResult.success(account); } }
接口很是简单,调用内置的getById
,但是却查出了全部相关的数据,这都是由于配置的那些注解。
能够看到其实发送了好几条SQL
。第一条是userAccountService.getById(1L)
,后面几条都是自动发送的。
实在不想贴太多代码,其实仍是挺简单的,源码地址还有示例地址都贴出来啦,有兴趣的能够去看一下。以为好用能够点个Star
。欢迎你们一块儿来贡献。