Spring Boot学习笔记(三)—— 添加Mybatis、Druid

一、前言

之前我们对Spring Boot的View和Control配置都有了一定的了解,在Model层配置上,我们将使用Mybatis、Druid进行开发,下面就对其进行配置。

二、开始配置

MyBatis 是一款优秀的持久层框架,Druid是一个高性能的数据库连接池,并且提供了监控功能,二者均提供了官方的starter pom来支持Spring Boot,我们只需引入依赖即可:

        <dependency>
            
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <scope>runtimescope>
        dependency>
        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>1.3.1version>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druid-spring-boot-starterartifactId>
            <version>1.1.6version>
        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之前,先引入一个插件来帮助我们自动生成代码。

        ...
            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.6
                
                    true
                    false
                
            
        ...

src/main/resources下新建文件generatorConfig.xml:





<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"/>
            
            <property name="suppressAllComments" value="true" />
        commentGenerator>
                                                            
        <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>
          
        <sqlMapGenerator targetPackage="com.hl.spring_boot_demo.domain.mapping" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        sqlMapGenerator>
        
        <javaClientGenerator type="XMLMAPPER" targetPackage="com.hl.spring_boot_demo.dao" targetProject="src/main/java">
            <property name="enableSubPackages" value="true"/>
        javaClientGenerator>
        
        <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及其简单,我们只需:

  1. 添加相应starter pom,数据库驱动
  2. 主类上添加@MapperScan自动扫描*Mapper.java
  3. 配置mapper-locations自动扫描*Mapper.xml
  4. 我们可以使用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

你可能感兴趣的:(Spring,Boot,Spring,Boot,Mybatis,Druid)