一、前言
之前我们对Spring Boot的View和Control配置都有了一定的了解,在Model层配置上,我们将使用Mybatis、Druid进行开发,下面就对其进行配置。
二、开始配置
MyBatis 是一款优秀的持久层框架,Druid是一个高性能的数据库连接池,并且提供了监控功能,二者均提供了官方的starter pom来支持Spring Boot,我们只需引入依赖即可:
<dependency>
<!-- mysql jdbc驱动 -->
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.6</version>
</dependency>
添加数据库连接配置:
# application.yml
spring:
datasource:
dirver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/spring_boot_demo?useUnicode=true&characterEncoding=utf8&useSSL=false
username: root
password: 123456
#druid相关配置可查看官方文档 https://github.com/alibaba/druid
druid:
initial-size: 3
max-active: 10
druid就算配置完了,在配置Mybatis之前,先引入一个插件来帮助我们自动生成代码。
...
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.6</version>
<configuration>
<verbose>true</verbose>
<overwrite>false</overwrite>
</configuration>
</plugin>
...
在src/main/resources
下新建文件generatorConfig.xml
:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 命令行执行命令:java -jar mybatis-generator-core-1.3.2.jar -configfile generatorConfig.xml -->
<!-- maven命令:mvn mybatis-generator:generate -->
<generatorConfiguration>
<!-- 驱动包路径! -->
<classPathEntry location="D:\software\myJar\MybatisGenerator\mysql-connector-java-5.1.38.jar"/>
<context id="MysqlTables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true" />
</commentGenerator>
<!-- jdbc url地址 ! -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/spring_boot_demo?useSSL=false" userId="root" password="123456">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 实体类生成位置 -->
<javaModelGenerator targetPackage="com.hl.spring_boot_demo.domain" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- mapping文件生成位置 -->
<sqlMapGenerator targetPackage="com.hl.spring_boot_demo.domain.mapping" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- dao接口生成位置 -->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.hl.spring_boot_demo.dao" targetProject="src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 表配置 tableName 表名 domainObjectName java类名,首字母必须大写,否则报字符串越界错误 -->
<table tableName="tb_user" domainObjectName="SysUser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
</table>
</context>
</generatorConfiguration>
然后在mysql里建一个表:
CREATE TABLE `tb_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
接下来就可以直接在eclipse里run as>maven build>mybatis-generator:generate
,刷新以下项目就会发现插件已经自动为我们生成了SysUserMapper.xml
,SysUser.hava
,SysUserMapper.java
,此时项目结构如下:
com
+- hl
+- spring_boot_demo
+- SpringBootDemoApplication.java
|
+- dao
| +- SysUserMapper.java
+- domain
| +- mapping
| +- SysUserMapper.xml
| +- SysUser.java
|
+- service
| +- CustomerService.java
|
+- web
+- CustomerController.java
接下来添加配置:
#application.yml
mybatis:
# mapper.xml的存放位置
mapper-locations: classpath:com/szb/application_manage_system/domain/mapping/*.xml
# 实体类包名
type-aliases-package: com.szb.application_manage_system.domain
# 完整Mybatis配置可查看官方文档 http://www.mybatis.org/mybatis-3/zh/configuration.html
configuration:
lazyLoadingEnabled: false
aggressiveLazyLoading: true
useGeneratedKeys: true
在主类上添加注释扫描接口类:
@MapperScan("com.hl.spring_boot_demo.dao")
public class SpringBootDemoApplication {
Druid、Mybatis已经配置完成,现在我们写个测试类测试以下crud。
//定义一个测试基类,后续测试直接继承
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = SpringBootDemoApplication.class)
public class BaseJunit4Test {
}
在src/test/java/com/hl/spring_boot_demo/domain
下新建UserTest.java
:
public class UserTest extends BaseJunit4Test{
@Autowired
SysUserMapper mapper;
@Test
@Transactional
//事务控制,为true则回滚
@Rollback(false)
public void testInsert() {
SysUser user = new SysUser();
user.setUsername("admin");
user.setPassword("123456");
mapper.insertSelective(user);
}
}
运行后查看是否成功,然后打开数据库查看数据是否已经插入。
三、总结
在Spring Boot中使用Duid、Mybatis及其简单,我们只需:
- 添加相应starter pom,数据库驱动
- 主类上添加
@MapperScan
自动扫描*Mapper.java
- 配置
mapper-locations
自动扫描*Mapper.xml
- 我们可以使用
mybatis-generator-maven-plugin
自动生成实体类、接口类和xml
更多关于Spring Boot整合Mybatis、Druid的详细说明可以参考官方文档:
mybatis: http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure
Druid: https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter