[TOC]
springboot 融合了很多插件。springboot相比spring来说有一下有点
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.3.RELEASE</version>
</parent>
复制代码
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
复制代码
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
复制代码
【详见feature/0002/spring-mybatis 分支】
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
复制代码
MybatisConfig @Bean
@ConfigurationProperties("spring.datasource")
public DataSource primaryDataSource() {
// 这里为了演示,暂时写死 。 实际上是可以通过autoConfigure装配参数的
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUsername("root");
dataSource.setPassword("123456");
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://192.168.44.130:3306/others?useUnicode=true&characterEncoding=utf8");
return dataSource;
}
复制代码
Bean 注解,就相当于我们在spring的xml中配置的bean标签。在java代码中我们可以进行我们业务处理。个人理解感觉更加的可控。 因为我们使用的mysql。所以这里我们简单的使用druid的数据源 @Bean
public SqlSessionFactory primarySqlSessionFactory() {
SqlSessionFactory factory = null;
try {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(primaryDataSource());
sqlSessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-primary.xml"));
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:/com/github/zxhtom.**./*.xml"));
factory = sqlSessionFactoryBean.getObject();
} catch (Exception e) {
e.printStackTrace();
}
return factory;
}
复制代码
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactory(primarySqlSessionFactory());
//每张表对应的*.java,interface类型的Java文件
mapperScannerConfigurer.setBasePackage("com.github.zxhtom.**.mapper");
return mapperScannerConfigurer;
}
复制代码
@Bean
public DataSourceTransactionManager primaryTransactionManager() {
return new DataSourceTransactionManager(dataSource);
}
复制代码
@Bean
public TransactionInterceptor txAdvice() {
DefaultTransactionAttribute txAttr_REQUIRED = new DefaultTransactionAttribute();
txAttr_REQUIRED.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
DefaultTransactionAttribute txAttr_REQUIRED_READONLY = new DefaultTransactionAttribute();
txAttr_REQUIRED_READONLY.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
txAttr_REQUIRED_READONLY.setReadOnly(true);
NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
source.addTransactionalMethod("add*", txAttr_REQUIRED);
source.addTransactionalMethod("save*", txAttr_REQUIRED);
source.addTransactionalMethod("delete*", txAttr_REQUIRED);
source.addTransactionalMethod("update*", txAttr_REQUIRED);
source.addTransactionalMethod("exec*", txAttr_REQUIRED);
source.addTransactionalMethod("set*", txAttr_REQUIRED);
source.addTransactionalMethod("get*", txAttr_REQUIRED_READONLY);
source.addTransactionalMethod("query*", txAttr_REQUIRED_READONLY);
source.addTransactionalMethod("find*", txAttr_REQUIRED_READONLY);
source.addTransactionalMethod("list*", txAttr_REQUIRED_READONLY);
source.addTransactionalMethod("count*", txAttr_REQUIRED_READONLY);
source.addTransactionalMethod("is*", txAttr_REQUIRED_READONLY);
return new TransactionInterceptor(primaryTransactionManager(), source);
}
复制代码
@Bean
public Advisor txAdviceAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
return new DefaultPointcutAdvisor(pointcut, txAdvice());
}@Bean
public Advisor txAdviceAdvisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
return new DefaultPointcutAdvisor(pointcut, txAdvice());
}
复制代码
@Configuration @Aspect @EnableTransactionManagement 复制代码
以上就是mybatis基本的一个配置了。但是这个时候还是不能使用的。因为我们的mapper对应的xml是放在java目录下的。正常src下都是java。xml文件在maven编译时不放行的。我们需要特殊处理下
在pom的build下加入放行配置
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.properties</include>
<include>**/*.yaml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
复制代码
@SpringBootTest(classes = Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public class TestDataSource {
@Autowired
private TestMapper testMapper;
@Test
public void test() {
List<Map<String, Object>> test = testMapper.test();
System.out.println(test);
}
}
复制代码
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
return new DruidDataSource();
}
复制代码
【详见feature/0002/spring-mybatis-tk-page 分支】
<dependency>
<groupId>tk.mybatis</groupId>
<artifactId>mapper</artifactId>
<version>3.3.9</version>
</dependency>
复制代码
这些插件其实就是改写我们之前学习的myabtis四大组件中的某一个组件而实现的。所以不管是通用mapper还是后面要说的myabtis-plus都是需要重新改写我们的myabtis配置类的。
首先我们想接入通用mapper时,我们需要改用tk提供的扫包配置
@Bean
public MapperScannerConfigurer mapperScannerConfigurer() {
tk.mybatis.spring.mapper.MapperScannerConfigurer mapperScannerConfigurer = new tk.mybatis.spring.mapper.MapperScannerConfigurer();
//MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setSqlSessionFactory(primarySqlSessionFactory());
//每张表对应的*.java,interface类型的Java文件
mapperScannerConfigurer.setBasePackage("com.github.zxhtom.**.mapper");
return mapperScannerConfigurer;
}
复制代码
@Bean()
public MapperHelper primaryMapperHelper() throws Exception {
MapperHelper mapperHelper = new MapperHelper();
Config config = mapperHelper.getConfig();
//表名字段名使用驼峰转下划线大写形式
config.setStyle(Style.camelhumpAndUppercase);
mapperHelper.registerMapper(Mapper.class);
mapperHelper.processConfiguration(primarySqlSessionFactory().getConfiguration());
return mapperHelper;
}
复制代码
User user = tkMapper.selectByPrimaryKey(1); 复制代码
【详见feature/0002/spring-mybatisplus 分支】
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
复制代码
@Data
@TableName(value = "person_info_large")
public class User {
@TableId(value = "id",type = IdType.AUTO)
private Integer id;
private String account;
private String name;
private String area;
private String title;
private String motto;
}
复制代码
public interface PlusMapper extends BaseMapper<User> {
}
复制代码
@Bean
public SqlSessionFactory primarySqlSessionFactory() {
SqlSessionFactory factory = null;
try {
MybatisSqlSessionFactoryBean sqlSessionFactoryBean = new MybatisSqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(primaryDataSource());
sqlSessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-primary.xml"));
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/github/zxhtom.**./*.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.github.zxhtom.**.model");
factory = sqlSessionFactoryBean.getObject();
} catch (Exception e) {
e.printStackTrace();
}
return factory;
}
复制代码
@Test
public void plusTest() {
User user = plusMapper.selectById(1);
System.out.println(user);
}
复制代码
【详见feature/0002/spring-mybatisplus 分支】
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
复制代码
return plusMapper.selectPage(page, null); 复制代码
【详见feature/0002/spring-mybatis-tk-page 分支】
因为myatis-plus自带了分页插件。上面也展示了如何使用myabtis-plus插件。还有一个github上开元的分页插件。这里就和通用mapper进行组合使用
pagehelper官方更新还是挺勤奋的。提供了pagehelper 和springboot auto装配两种。 笔者这里测试了 pagehelper-spring-boot-starter 这个包不适合本案例中。因为本案例中扫描mapper路径是通过 MapperScannerConfigurer 注册的。如果使用 pagehelper-spring-boot-starter 的话就会导致分页拦截器失效。我们看看源码
MapperScannerConfigurer . 经过笔者测试。需要在MybatisConfig类上添加扫描注解 @MapperScan(basePackages = {"com.github.zxhtom.**.mapper"}, sqlSessionFactoryRef = "primarySqlSessionFactory") <dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.7</version>
</dependency>
复制代码
SqlSessionFactoryBean 设置 sqlSessionFactoryBean.setPlugins(new Interceptor[]{new PageInterceptor()}); 。 @Bean
public SqlSessionFactory primarySqlSessionFactory() {
SqlSessionFactory factory = null;
try {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(primaryDataSource());
sqlSessionFactoryBean.setConfigLocation(new DefaultResourceLoader().getResource("classpath:mybatis-primary.xml"));
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:com/github/zxhtom.**./*.xml"));
sqlSessionFactoryBean.setTypeAliasesPackage("com.github.zxhtom.**.model");
sqlSessionFactoryBean.setPlugins(new Interceptor[]{new PageInterceptor()});
factory = sqlSessionFactoryBean.getObject();
} catch (Exception e) {
e.printStackTrace();
}
return factory;
}
复制代码
这里简单阐述下为什么不适用注解扫描mapper、或者不在配置文件中配置扫包路径。因为通过 MapperScannerConfigurer 我们可以动态控制路径。这样显得比较有逼格。在实际开发中笔者推荐使用注解方式扫描。因为这样可以避免不必要的坑。
到这里我们整理了【springboot整合mybaits】、【mybatis-plus】、【通用mapper】、【pagehelper插件整合】 这四个模块的整理中我们发现离不开myabtis的四大组件。springboot其实我们还未接触到深的内容。这篇文章主要偏向myabtis . 后续还会继续衍生探索 【myabtis+druid】监控数据信息 。
喜欢研究源码和开元框架小试牛刀的欢迎关注我
代码仓库: gitee.com/zxhTom/spri…