美文网首页
SpringBoot整合mybatis

SpringBoot整合mybatis

作者: landlord_ | 来源:发表于2019-03-20 19:30 被阅读0次
    摘要:SpringBoot遵循约定大于配置的原则,整合mybatis只需要简单配置即可使用。

    首先,新建SpringBoot工程,并引入相关依赖。包含mybatis、connector、druid
    maven依赖如下:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.test</groupId>
      <artifactId>SpringBoot-mybatis</artifactId>
      <version>0.0.1-SNAPSHOT</version>
    
      <name>SpringBoot-mybatis</name>
      <url>http://www.example.com</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
      </properties>
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.1.RELEASE</version>
        </parent>
    
      <dependencies>
        <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>
        <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</artifactId>                
            <version>1.0.9</version>            
        </dependency>
       <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
      </dependencies>
      <build>
            <plugins>
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.2</version>
                    <configuration>
                        <!-- mybatis用于生成代码的配置文件 -->
                        <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    
    搭建项目结构,创建存放controller、model、mapper的包,及配置文件,如图:
    项目结构
    配置文件:
    application.yml,配置数据库及连接池信息:
    server:
      port: 9310
    
    spring:
      application:
        name: contract-server
      datasource:
        name: test
        url: jdbc:mysql://127.0.0.1:3306/'dataName'
        username: root
        password: admin
        # 使用druid数据源
        type: com.alibaba.druid.pool.DruidDataSource
        driver-class-name: com.mysql.jdbc.Driver
        filters: stat
        maxActive: 20
        initialSize: 1
        maxWait: 60000
        minIdle: 1
        timeBetweenEvictionRunsMillis: 60000
        minEvictableIdleTimeMillis: 300000
        validationQuery: select 'x'
        testWhileIdle: true
        testOnBorrow: false
        testOnReturn: false
        poolPreparedStatements: true
        maxOpenPreparedStatements: 20
    
    application.properties文件,
    配置扫描xml位置及model位置,虽然可用注解写sql,但xml相对更灵活,如动态sql,字段映射等
    #对象位置
    mybatis.type-aliases-package=com.test.model
    #xml文件位置
    mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
    
    可使用generator根据数据库自动生成代码

    配置如下:

    <?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">
    
    <generatorConfiguration>
        <classPathEntry location="D:/01_Work/repository/mysql/mysql-connector-java/5.1.46/mysql-connector-java-5.1.46.jar" />
        <context id="MysqlContext" targetRuntime="MyBatis3" defaultModelType="flat">
            <property name="beginningDelimiter" value="`"/>
            <property name="endingDelimiter" value="`"/>
    
            <commentGenerator>
            <!--         阻止生成注释 -->
                <property name="suppressAllComments" value="true"/>
            <!--         阻止生成时间戳 -->
                <property name="suppressDate" value="true"/>
            </commentGenerator>
            <!--    数据库配置    -->
            <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                            connectionURL="jdbc:mysql://localhost:3306/datebaseName"
                            userId="root"
                            password="admin">
            </jdbcConnection>
    
            <javaModelGenerator targetPackage="com.test.model" targetProject="./src/main/java">
                <property name="trimStrings" value="true" />
                <property name="enableSubPackages" value="true" />
            </javaModelGenerator>
    
            <sqlMapGenerator targetPackage="mybatis/mapper"  targetProject="./src/main/resources">
            <property name="enableSubPackages" value="true" />
            </sqlMapGenerator>
    
            <javaClientGenerator type="XMLMAPPER" targetPackage="com.test.mybatis.mapper"  targetProject="./src/main/java"/>
    
            <table tableName="contract" domainObjectName="Contract">
                <generatedKey column="id" sqlStatement="Mysql" identity="true" />
            </table>
        </context>
    </generatorConfiguration>
    

    generator详细配置:https://blog.csdn.net/xp_lx1/article/details/80074738
    现在使用maven插件自动生成model、mapper、及xml文件.

    数据库建表并录入数据
    data

    插件已在maven中引入,右击工程>>run as>>maven build>>
    执行:mybatis-generator:generate


    执行generateor success

    刷新项目:


    标准四件套

    现在我们可以写controller代码:

    
    @RestController
    public class TestController {
        //注入mapper
        @Autowired
        ContractMapper contractmapper;
        
        @RequestMapping("getList")
        public List<Contract> getList(){
            List<Contract> contractList = contractmapper.selectByExample(null);
            return contractList;
        }
    }
    

    创建启动类并启动项目:

    @SpringBootApplication
    //此处增加扫描注解
    @MapperScan("com.test.mybatis")
    public class App 
    {
        public static void main( String[] args )
        {
            SpringApplication.run(App.class, args);
        }
    }
    
    
    浏览器输入:http://127.0.0.1:9310/getList

    得到结果:


    result

    success!

    相关文章

      网友评论

          本文标题:SpringBoot整合mybatis

          本文链接:https://www.haomeiwen.com/subject/vxvtvqtx.html