SpringBoot资料合集-05【Spring Boot集成MyBatis】

20 篇文章 1 订阅
16 篇文章 1 订阅

1.整合Durid数据源

1、引入Jar包

1
2 <dependencies> 
3 <dependency> 
4 <groupId>org.springframework.boot</groupId> 
5 <artifactId>spring‐boot‐starter‐jdbc</artifactId> 
6 </dependency> 
7 <dependency> 
8 <groupId>org.springframework.boot</groupId> 
9 <artifactId>spring‐boot‐starter‐web</artifactId> 
10 </dependency> 
11 <!‐‐mybatis的场景启动器 
12 因为MyBatis它是Spring data jpa 
13 <dependency> 
14 <groupId>org.mybatis.spring.boot</groupId> 
15 <artifactId>mybatis‐spring‐boot‐starter</artifactId> 
16 <version>2.1.4</version> 
17 </dependency> 
18 ‐‐> 
19 <dependency> 
20 <groupId>com.alibaba</groupId> 
21 <artifactId>druid</artifactId> 
22 <version>1.2.3</version> 
23 </dependency>
24
25 <dependency> 
26 <groupId>mysql</groupId> 
27 <artifactId>mysql‐connector‐java</artifactId> 
28 <scope>runtime</scope> 
29 </dependency> 
30 <dependency> 
31 <groupId>org.springframework.boot</groupId> 
32 <artifactId>spring‐boot‐starter‐test</artifactId> 
33 <scope>test</scope> 
34 </dependency> 
35 </dependencies> 

2.application.yml配置

1 #数据源 
2 spring: 
3 datasource: 
4 username: root 
5 password: 123456 
6 url: jdbc:mysql://localhost:3306/springboot_mybatis?characterEn 
coding=utf8&useSSL=false&serverTimezone=UTC& 
7 driver‐class‐name: com.mysql.cj.jdbc.Driver 
8 type: com.alibaba.druid.pool.DruidDataSource 
9
10 # 数据源其他配置 
11 initialSize: 5 
12 minIdle: 5 
13 maxActive: 20 
14 maxWait: 60000 
15 timeBetweenEvictionRunsMillis: 60000 
16 minEvictableIdleTimeMillis: 300000 
17 validationQuery: SELECT 1 FROM DUAL 
18 testWhileIdle: true 
19 testOnBorrow: false 
20 testOnReturn: false
21 poolPreparedStatements: true 
22 # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于 
防火墙 
23 filters: stat,wall 
24 maxPoolPreparedStatementPerConnectionSize: 20 
25 useGlobalDataSourceStat: true 
26 connectionProperties: druid.stat.mergeSql=true;druid.stat.slow 
SqlMillis=500 
27 schema: classpath:sql/mybatis.sql 
28 initialization‐mode: ALWAYS 

3.读取配置类DruidConfig

1 /** 
2 * 数据源配置类 
3 */ 
4 @Configuration 
5 public class DruidConfig { 
6 // 将所有前缀为spring.datasource下的配置项都加载到DataSource中 
7 @ConfigurationProperties(prefix = "spring.datasource") 
8 @Bean 
9 public DataSource druidDataSource() { 
10 return new DruidDataSource(); 
11 } 
12
13 @Bean 
14 public ServletRegistrationBean statViewServlet() { 
15 ServletRegistrationBean servletRegistrationBean = new ServletR 
egistrationBean(new StatViewServlet(), "/druid/*"); 
16 // 添加IP白名单 
17 servletRegistrationBean.addInitParameter("allow", 
"127.0.0.1"); 
18 // 添加IP黑名单,当白名单和黑名单重复时,黑名单优先级更高 
19 servletRegistrationBean.addInitParameter("deny", "127.0.0.1"); 
20 // 添加控制台管理用户 
21 servletRegistrationBean.addInitParameter("loginUsername", "adm 
in"); 
22 servletRegistrationBean.addInitParameter("loginPassword", "123 
456");
23 // 是否能够重置数据 
24 servletRegistrationBean.addInitParameter("resetEnable", "fals 
e"); 
25 return servletRegistrationBean; 
26 } 
27
28 /** 
29 * 配置服务过滤器 
30 * 
31 * @return 返回过滤器配置对象 
32 */ 
33 @Bean 
34 public FilterRegistrationBean statFilter() { 
35 FilterRegistrationBean filterRegistrationBean = new FilterRegi 
strationBean(new WebStatFilter()); 
36 // 添加过滤规则 
37 filterRegistrationBean.addUrlPatterns("/*"); 
38 // 忽略过滤格式 
39 filterRegistrationBean.addInitParameter("exclusions", "*.js,*. 
gif,*.jpg,*.png,*.css,*.ico,/druid/*,"); 
40 return filterRegistrationBean; 
41 } 
42 } 

其实没有必要一个个手动去配置, druid 启动starter

1 <dependency> 
2 <groupId>com.alibaba</groupId> 
3 <artifactId>druid‐spring‐boot‐starter</artifactId> 
4 <version>1.2.3</version> 
5 </dependency> 

druid 自动配置类

1
2 @Configuration 
3 @ConditionalOnClass(DruidDataSource.class) 
4 @AutoConfigureBefore(DataSourceAutoConfiguration.class)
5 @EnableConfigurationProperties({DruidStatProperties.class, DataS 
ourceProperties.class}) 
6 @Import({DruidSpringAopConfiguration.class, 
7 DruidStatViewServletConfiguration.class, 
8 DruidWebStatFilterConfiguration.class, 
9 DruidFilterConfiguration.class}) 
10 public class DruidDataSourceAutoConfigure { 
11
12 private static final Logger LOGGER = LoggerFactory.getLogger(D 
ruidDataSourceAutoConfigure.class); 
13
14 @Bean(initMethod = "init") 
15 @ConditionalOnMissingBean 
16 public DataSource dataSource() { 
17 LOGGER.info("Init DruidDataSource"); 
18 return new DruidDataSourceWrapper(); 
19 } 
20 } 

2.整合MyBatis

2.1生成MyBatis代码:

pom.xml

1 <!‐‐ MybatisGenerator插件,自动生成代码 ‐‐> 
2 <plugin> 
3 <groupId>org.mybatis.generator</groupId> 
4 <artifactId>mybatis‐generator‐maven‐plugin</artifactId> 
5 <version>1.3.5</version> 
6 <configuration> 
7 <configurationFile>${project.basedir}/src/main/resources/genera 
torConfig.xml</configurationFile> 
8 <verbose>true</verbose> 
9 <overwrite>true</overwrite> 
10 </configuration> 
11 <dependencies> 
12 <!‐‐必須要引入数据库驱动‐‐>
13 <dependency> 
14 <groupId>mysql</groupId> 
15 <artifactId>mysql‐connector‐java</artifactId> 
16 <!‐‐必须制定版本‐‐> 
17 <version>8.0.22</version> 
18 </dependency> 
19 </dependencies> 
20 </plugin> 
21 </plugins> 
22 </build> 

generatorConfig.xml

1
2
3 <!DOCTYPE generatorConfiguration PUBLIC 
4 "‐//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN" 
5 "http://mybatis.org/dtd/mybatis‐generator‐config_1_0.dtd"> 
6 <generatorConfiguration> 
7
8
9 <!‐‐如果需要使用 command的方式生成需要配置数据库驱动的jar包路径 
10 <classPathEntry location="指定数据驱动的磁盘路径"/>‐‐> 
11
12 <!‐‐context 生成上下文 配置生成规则 
13 id 随意写 
14 targetRuntime 生成策略 
15 MyBatis3DynamicSql 默认的,会生成 动态生成sql的方式(没有xml) 
16 MyBatis3 生成通用的查询,可以指定动态where条件 
17 MyBatis3Simple 只生成简单的CRUD 
18 ‐‐> 
19 <context id="simple" targetRuntime="MyBatis3Simple"> 
20
21
22 <commentGenerator>
23 <!‐‐设置是否生成注释 true 不生成 注意: 如果不生成注释,下次生成代码 
就不会进行合并‐‐> 
24 <property name="suppressAllComments" value="true"/> 
25 </commentGenerator> 
26 <!‐‐数据源 ‐‐> 
27 <jdbcConnection driverClass="com.mysql.jdbc.Driver" 
28 connectionURL="jdbc:mysql://localhost:3306/mybatis" 
29 userId="root" 
30 password="123456"/> 
31
32 <!‐‐pojo 
33 javaModelGenerator java实体生成规则(POJO) 
34 targetPackage 生成到哪个包下 
35 targetProject 生成到当前文件的哪个相对路径下 
36 ‐‐> 
37 <javaModelGenerator targetPackage="cn.tulingxueyuan.pojo" targ 
etProject="src/main/java"/> 
38 <!‐‐mapper xml映射文件 
39 sqlMapGenerator mapper xml映射文件生成规则 
40 targetPackage 生成到哪个包下 
41 targetProject 生成到当前文件的哪个相对路径下 
42 ‐‐> 
43 <sqlMapGenerator targetPackage="cn.tulingxueyuan.mapper" targe 
tProject="src/main/resources"></sqlMapGenerator> 
44 <!‐‐mapper接口 
45 javaClientGenerator mapper mapper接口生成规则 
46 type 指定生成的方式 
47 1.使用注解的方式生成 
48 2.使用接口绑定的方式生成(要配置sqlMapGenerator) 
49 targetPackage 生成到哪个包下 
50 targetProject 生成到当前文件的哪个相对路径下‐‐> 
51 <javaClientGenerator type="XMLMAPPER" targetPackage="cn.tuling 
xueyuan.mapper" targetProject="src/main/java"/> 
52
53
54 <!‐‐配置哪些表需要进行代码生成
55 tableName 表名 
56 domainObjectName pojo类名 
57 mapperName 对应mapper接口的类名 和 mapper xml文件名 
58 ‐‐> 
59 <table tableName="emp" domainObjectName="Emp" mapperName="EmpM 
apper" /> 
60 <table tableName="dept" domainObjectName="Dept" mapperName="De 
ptMapper" /> 
61 </context> 
62 </generatorConfiguration> 

运行插件—生成代码
在这里插入图片描述

2.2 整合Mybatis

1.引入jar包

1
2 1、引入Jar3 <dependency> 
4 <groupId>org.mybatis.spring.boot</groupId> 
5 <artifactId>mybatis‐spring‐boot‐starter</artifactId> 
6 <version>1.3.2</version>
7 </dependency> 
8
9

application.yml

1 mybatis: 
2 # 映射文件所在路径 
3 mapper‐locations: classpath:mappers/*.xml 
4 # pojo类所在包路径 
5 type‐aliases‐package: com.cx.user.model 

MyBatis自动配置原理

1 @Bean 
2 @ConditionalOnMissingBean 
3 public SqlSessionFactory sqlSessionFactory(DataSource 
dataSource) throws Exception { 
4 SqlSessionFactoryBean factory = new SqlSessionFactoryBean(); 
5 factory.setDataSource(dataSource); 
6 factory.setVfs(SpringBootVFS.class); 
7
8 // 设置Mybaits的全局配置文件 
9 if (StringUtils.hasText(this.properties.getConfigLocation())) { 
10
factory.setConfigLocation(this.resourceLoader.getResource(this.pro 
perties.getConfigLocation())); 
11 } 
12 // ? 有另一种定制方式的体现 
13 applyConfiguration(factory); 
14 // 相当于mybatis全局配置文件中 
15 /*<properties> 
16 <property name="" value=""/> 
17 </properties>*/ 
18 if (this.properties.getConfigurationProperties() != null) { 
19 factory.setConfigurationProperties(this.properties.getConfigur 
ationProperties()); 
20 } 
21 // 就是配置插件‐拦截器 只需要配置一个实现了Interceptor的接口为Bean
22 if (!ObjectUtils.isEmpty(this.interceptors)) { 
23 factory.setPlugins(this.interceptors); 
24 } 
25 // 设置数据库厂商id 
26 if (this.databaseIdProvider != null) { 
27 factory.setDatabaseIdProvider(this.databaseIdProvider); 
28 } 
29 // 设置别名:去application.yml中獲取mybatis.typeAliasesPackage 
30 if (StringUtils.hasLength(this.properties.getTypeAliasesPackag 
e())) { 
31 factory.setTypeAliasesPackage(this.properties.getTypeAliasesPa 
ckage()); 
32 } 
33 // 可以通过父类过滤哪些类需要使用别名 
34 比如:pojo.user extends basePojo 
35 pojo.user2 
36 去application.yml中设置mybatis.typeAliasesSuperType: com.tuling 
xueyuan.pojo.basePojo 
37 if (this.properties.getTypeAliasesSuperType() != null) { 
38 factory.setTypeAliasesSuperType(this.properties.getTypeAliases 
SuperType()); 
39 } 
40 // 设置类型处理器 
41 <typeHandlers> 
42 <package name=""/> 
43 </typeHandlers> 
44 if (StringUtils.hasLength(this.properties.getTypeHandlersPacka 
ge())) { 
45 factory.setTypeHandlersPackage(this.properties.getTypeHandlers 
Package()); 
46 } 
47 // 设置类型处理器 
48 <typeHandlers> 
49 <typeHandler handler="" 
50 </typeHandlers> 
51 if (!ObjectUtils.isEmpty(this.typeHandlers)) { 
52 factory.setTypeHandlers(this.typeHandlers);
53 } 
54 // 设置mapper.xml映射文件:mapper‐locations: classpath:com/tulin 
gxueyuan/mapper/*Mapper.xml 
55 if (!ObjectUtils.isEmpty(this.properties.resolveMapperLocation 
s())) { 
56 factory.setMapperLocations(this.properties.resolveMapperLocati 
ons()); 
57 } 
58 Set<String> factoryPropertyNames = Stream 
59 .of(new BeanWrapperImpl(SqlSessionFactoryBean.class).getProper 
tyDescriptors()).map(PropertyDescriptor::getName) 
60 .collect(Collectors.toSet()); 
61 Class<? extends LanguageDriver> defaultLanguageDriver = this.p 
roperties.getDefaultScriptingLanguageDriver(); 
62 if (factoryPropertyNames.contains("scriptingLanguageDrivers") 
&& !ObjectUtils.isEmpty(this.languageDrivers)) { 
63 // Need to mybatis‐spring 2.0.2+ 
64 factory.setScriptingLanguageDrivers(this.languageDrivers); 
65 if (defaultLanguageDriver == null && this.languageDrivers.leng 
th == 1) { 
66 defaultLanguageDriver = this.languageDrivers[0].getClass(); 
67 } 
68 } 
69 if (factoryPropertyNames.contains("defaultScriptingLanguageDri 
ver")) { 
70 // Need to mybatis‐spring 2.0.2+ 
71 factory.setDefaultScriptingLanguageDriver(defaultLanguageDrive 
r); 
72 } 
73
74 return factory.getObject(); 
75 } 

该文章后续及其配套资料+代码,关注我,免费领取!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值