# mp-extra **Repository Path**: github-26359270/mp-extra ## Basic Information - **Project Name**: mp-extra - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 5 - **Forks**: 0 - **Created**: 2021-03-11 - **Last Updated**: 2022-08-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # mp-extra this is a great tools to improve mybatis plus,with this tools , you can auto select from many tables from database at one times without other sql > 项目中有sql文件 resources/data.sql #### 添加依赖,已经发布到中央仓库了,可以直接使用: ```xml top.lww0511 mp-extra 1.0.1 ``` #### 在启动类上添加注解 `@EnableMpExtra` #### 配置拦截器 因为一般项目都会配置自己的`MybatisConfiguration`,我在这里配置后,打包,然后被引入,是无法生效的。 所以就想了一种折中的方法。 以前`MybatisConfiguration`是通过`new`出来的,现在通过`MybatisExtraConfig.getMPConfig();`来获取,这样获取到的`MybatisConfiguration`就已经添加好了拦截器。 完整`Mybatis-Plus`配置类例子,注意第43行: ```java @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); 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); } } ``` #### 在实体类上建立关系 ```java @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @ApiModel(value = "UserAccount对象", description = "用户相关") public class UserAccount extends Model { 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 hobbies; @TableField(exist = false) @Many2Many(self = "id", leftMid = "user_id", rightMid = "class_id", origin = "id" , midMapper = UserMidClassMapper.class, mapper = UserClassMapper.class) private List classes; @Override protected Serializable pkVal() { return this.id; } } ``` 主要是那几个注解。对了还要加`@TableField(exist = false)`,不然会报错。 #### 测试接口 ```java @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`。欢迎大家一起来贡献。 GitHub: https://github.com/LerDer/mp-extra 示例 https://gitee.com/github-26359270/mp-extra-demo 最后欢迎大家关注我的公众号,共同学习,一起进步。加油🤣