Spring Boot Mybatis 整合

来源:互联网 发布:linux snmp起不来 编辑:程序博客网 时间:2024/06/18 08:21

本项目使用的环境:

  • 开发工具:Intellij IDEA 2017.1.3
  • jdk:1.7.0_79
  • 3.maven:3.3.9

额外功能

  • PageHelper 分页插件
  • mybatis generator 自动生成代码插件
步骤:

1.创建一个springboot项目:

这里写图片描述


2.创建项目的文件结构以及jdk的版本

这里写图片描述


3.选择项目所需要的依赖

这里写图片描述


这里写图片描述


看一下项目的结构:

这里写图片描述


4.项目不使用application.properties文件 而使用更加简洁的application.yml文件:
将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件,
文件的内容如下:

server:  port: 8080spring:    datasource:        name: test        url: jdbc:mysql://127.0.0.1:3306/depot        username: root        password: root        # 使用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: 20mybatis:  mapper-locations: classpath:mapping/*.xml  type-aliases-package: com.winter.model#pagehelper分页插件pagehelper:    helperDialect: mysql    reasonable: true    supportMethodsArguments: true    params: count=countSql

4.1 application.properties文件

spring.datasource.url=jdbc:mysql://localhost:3306/mytestdb?useUnicode=true&characterEncoding=UTF-8spring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driverspring.datasource.max-active=10spring.datasource.max-idle=5spring.datasource.min-idle=0

5.创建数据库


6.使用mybatis generator 自动生成代码:

6.1 配置pom.xml中generator 插件所对应的配置文件 ${basedir}/src/main/resources/generator/generatorConfig.xml

pom.xml文件:

<!-- mybatis generator 自动生成代码插件 -->            <plugin>                <groupId>org.mybatis.generator</groupId>                <artifactId>mybatis-generator-maven-plugin</artifactId>                <version>1.3.2</version>                <configuration>                    <configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>                    <overwrite>true</overwrite>                    <verbose>true</verbose>                </configuration>            </plugin>


generatorConfig.xml模板:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE generatorConfiguration  
  3.         PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"  
  4.         "http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">  
  5. <generatorConfiguration>  
  6.     <!--导入属性配置 -->  
  7.     <properties resource="generator.properties"></properties>  
  8.   
  9.     <!--指定特定数据库的jdbc驱动jar包的位置 -->  
  10.     <classPathEntry location="${jdbc.driverLocation}"/>  
  11.   
  12.     <context id="default" targetRuntime="MyBatis3">  
  13.   
  14.   
  15.         <!-- optional,旨在创建class时,对注释进行控制 -->  
  16.         <commentGenerator>  
  17.             <property name="suppressDate" value="true" />  
  18.         </commentGenerator>  
  19.   
  20.   
  21.         <!--jdbc的数据库连接 -->  
  22.         <jdbcConnection driverClass="${jdbc.driverClass}" connectionURL="${jdbc.connectionURL}" userId="${jdbc.userId}" password="${jdbc.password}">  
  23.         </jdbcConnection>  
  24.   
  25.   
  26.   
  27.         <!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->  
  28.         <javaTypeResolver >  
  29.             <property name="forceBigDecimals" value="false" />  
  30.         </javaTypeResolver>  
  31.   
  32.         <!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类  
  33.             targetPackage     指定生成的model生成所在的包名  
  34.             targetProject     指定在该项目下所在的路径  
  35.         -->  
  36.         <javaModelGenerator targetPackage="org.louis.hometutor.po" targetProject="src/main/java">  
  37.             <!-- 是否对model添加 构造函数 -->  
  38.             <property name="constructorBased" value="true"/>  
  39.   
  40.             <!-- 是否允许子包,即targetPackage.schemaName.tableName -->  
  41.             <property name="enableSubPackages" value="false"/>  
  42.   
  43.             <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->  
  44.             <property name="immutable" value="true"/>  
  45.   
  46.             <!-- 给Model添加一个父类 -->  
  47.             <property name="rootClass" value="com.foo.louis.Hello"/>  
  48.   
  49.             <!-- 是否对类CHAR类型的列的数据进行trim操作 -->  
  50.             <property name="trimStrings" value="true"/>  
  51.         </javaModelGenerator>  
  52.   
  53.         <!--Mapper映射文件生成所在的目录 为每一个数据库的表生成对应的SqlMap文件 -->  
  54.         <sqlMapGenerator targetPackage="org.louis.hometutor.domain" targetProject="src/main/java">  
  55.             <property name="enableSubPackages" value="false"/>  
  56.         </sqlMapGenerator>  
  57.   
  58.   
  59.         <!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码  
  60.                 type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象  
  61.                 type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象  
  62.                 type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口  
  63.         -->  
  64.         <javaClientGenerator targetPackage="com.foo.tourist.dao" targetProject="src/main/java" type="MIXEDMAPPER">  
  65.             <property name="enableSubPackages" value=""/>  
  66.             <!--  
  67.                     定义Maper.java 源代码中的ByExample() 方法的可视性,可选的值有:  
  68.                     public;  
  69.                     private;  
  70.                     protected;  
  71.                     default  
  72.                     注意:如果 targetRuntime="MyBatis3",此参数被忽略  
  73.              -->  
  74.             <property name="exampleMethodVisibility" value=""/>  
  75.             <!--  
  76.                                            方法名计数器  
  77.               Important note: this property is ignored if the target runtime is MyBatis3.  
  78.              -->  
  79.             <property name="methodNameCalculator" value=""/>  
  80.   
  81.             <!-- 
  82.                                                 为生成的接口添加父接口 
  83.              -->  
  84.             <property name="rootInterface" value=""/>  
  85.   
  86.         </javaClientGenerator>  
  87.   
  88.   
  89.   
  90.         <table tableName="lession" schema="louis">  
  91.   
  92.             <!-- optional   , only for mybatis3 runtime  
  93.                  自动生成的键值(identity,或者序列值)  
  94.                如果指定此元素,MBG将会生成<selectKey>元素,然后将此元素插入到SQL Map的<insert> 元素之中  
  95.                sqlStatement 的语句将会返回新的值  
  96.                如果是一个自增主键的话,你可以使用预定义的语句,或者添加自定义的SQL语句. 预定义的值如下:  
  97.                   Cloudscape    This will translate to: VALUES IDENTITY_VAL_LOCAL()  
  98.                   DB2:      VALUES IDENTITY_VAL_LOCAL()  
  99.                   DB2_MF:       SELECT IDENTITY_VAL_LOCAL() FROM SYSIBM.SYSDUMMY1  
  100.                   Derby:        VALUES IDENTITY_VAL_LOCAL()  
  101.                   HSQLDB:   CALL IDENTITY()  
  102.                   Informix:     select dbinfo('sqlca.sqlerrd1') from systables where tabid=1  
  103.                   MySql:        SELECT LAST_INSERT_ID()  
  104.                   SqlServer:    SELECT SCOPE_IDENTITY()  
  105.                   SYBASE:   SELECT @@IDENTITY  
  106.                   JDBC:     This will configure MBG to generate code for MyBatis3 suport of JDBC standard generated keys. This is a database independent method of obtaining the value from identity columns.  
  107.                   identity: 自增主键  If true, then the column is flagged as an identity column and the generated <selectKey> element will be placed after the insert (for an identity column). If false, then the generated <selectKey> will be placed before the insert (typically for a sequence).  
  108.   
  109.             -->  
  110.             <generatedKey column="" sqlStatement="" identity="" type=""/>  
  111.   
  112.   
  113.             <!-- optional.  
  114.                     列的命名规则:  
  115.                     MBG使用 <columnRenamingRule> 元素在计算列名的对应 名称之前,先对列名进行重命名,  
  116.                     作用:一般需要对BUSI_CLIENT_NO 前的BUSI_进行过滤  
  117.                     支持正在表达式  
  118.                      searchString 表示要被换掉的字符串  
  119.                      replaceString 则是要换成的字符串,默认情况下为空字符串,可选  
  120.             -->  
  121.             <columnRenamingRule searchString="" replaceString=""/>  
  122.   
  123.   
  124.   
  125.             <!-- optional.告诉 MBG 忽略某一列  
  126.                     column,需要忽略的列  
  127.                     delimitedColumnName:true ,匹配column的值和数据库列的名称 大小写完全匹配,false 忽略大小写匹配  
  128.                     是否限定表的列名,即固定表列在Model中的名称  
  129.             -->  
  130.             <ignoreColumn column="PLAN_ID"  delimitedColumnName="true" />  
  131.   
  132.   
  133.             <!--optional.覆盖MBG对Model 的生成规则  
  134.                  column: 数据库的列名  
  135.                  javaType: 对应的Java数据类型的完全限定名  
  136.                  在必要的时候可以覆盖由JavaTypeResolver计算得到的java数据类型. For some databases, this is necessary to handle "odd" database types (e.g. MySql's unsigned bigint type should be mapped to java.lang.Object).  
  137.                  jdbcType:该列的JDBC数据类型(INTEGER, DECIMAL, NUMERIC, VARCHAR, etc.),该列可以覆盖由JavaTypeResolver计算得到的Jdbc类型,对某些数据库而言,对于处理特定的JDBC 驱动癖好 很有必要(e.g. DB2's LONGVARCHAR type should be mapped to VARCHAR for iBATIS).  
  138.                  typeHandler:  
  139.   
  140.             -->  
  141.             <columnOverride column="" javaType=""    jdbcType="" typeHandler=""  delimitedColumnName="" />  
  142.   
  143.         </table>  
  144.     </context>  
  145. </generatorConfiguration> 

6.2 点击run-Edit Configuration
这里写图片描述


6.3 添加配置

这里写图片描述


6.4 运行

这里写图片描述


6.5 生成后还需要修改类中的路径,对呀mapper 文件可以使用快捷的方式把多余的代码一次性删除

ctrl + f 搜索需要删除的代码,然后进行下一步:

这里写图片描述


这里写图片描述


对于sql语句这种黄色的背景,解决方案:

这里写图片描述


7. 写一个Spring Boot 的启动类

package com.winter;import org.mybatis.spring.annotation.MapperScan;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@MapperScan("com.winter.mapper")//将项目中对应的mapper类的路径加进来就可以了(对应的接口的类路径)public class SpringbootMybatisDemoApplication {    public static void main(String[] args) {        SpringApplication.run(SpringbootMybatisDemoApplication.class, args);    }}

8.测试我使用了idea一个很用心的功能。
可以发http请求的插件

这里写图片描述



原创粉丝点击