美文网首页
Spring Boot整合Mybatis

Spring Boot整合Mybatis

作者: 努力耕耘少问收获 | 来源:发表于2019-03-12 00:15 被阅读0次

    Spring Boot中使用MyBatis

    1.首先需要搭建一个Spring Boot应用,包含基本的增删改查。这里数据层框架采用MyBatis,并集成了通用Mapper插件,实现单表快速地增删改查:
    2.MyBatis之前,先搭建一个基本的Spring Boot项目[开启Spring Boot]然后引入mybatis-spring-boot-starter和数据库连接驱动(这里使用关系型数据库MySQL)。

    1. 在pom中引入mybatis-spring-boot-starter
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.1</version>
    </dependency>
    

    不同版本的Spring Boot和MyBatis版本对应不一样,具体可查看官方文档:http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/

    通过dependency:tree命令查看mybatis-spring-boot-starter都有哪些隐性依赖:

    +- org.mybatis.spring.boot:mybatis-spring-boot-starter:jar:1.3.1:compile
    |  +- org.springframework.boot:spring-boot-starter-jdbc:jar:1.5.9.RELEASE:compile
    |  |  +- org.apache.tomcat:tomcat-jdbc:jar:8.5.23:compile
    |  |  |  \- org.apache.tomcat:tomcat-juli:jar:8.5.23:compile
    |  |  \- org.springframework:spring-jdbc:jar:4.3.13.RELEASE:compile
    |  |     \- org.springframework:spring-tx:jar:4.3.13.RELEASE:compile
    |  +- org.mybatis.spring.boot:mybatis-spring-boot-autoconfigure:jar:1.3.1:compile
    |  +- org.mybatis:mybatis:jar:3.4.5:compile
    |  \- org.mybatis:mybatis-spring:jar:1.3.1:compile
    
    2.引入MySQL驱动
    <!-- MySQL驱动 -->
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
            </dependency>
    
    3.Druid数据源

    Druid是一个关系型数据库连接池,是阿里巴巴的一个开源项目,地址:https://github.com/alibaba/druid。Druid不但提供连接池的功能,还提供监控功能,可以实时查看数据库连接池和SQL查询的工作情况。

    <!-- druid数据源驱动 -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>druid-spring-boot-starter</artifactId>
                <version>1.1.10</version>
            </dependency>
    
    4.Druid数据源配置

    上面通过查看mybatis starter的隐性依赖发现,Spring Boot的数据源配置的默认类型是org.apache.tomcat.jdbc.pool.Datasource,为了使用Druid连接池,需要在application.yml下配置:

    spring:
      datasource:
        druid:
          # 数据库访问配置, 使用druid数据源
          type: com.alibaba.druid.pool.DruidDataSource
          driver-class-name: com.mysql.jdbc.Driver
          url: jdbc:mysql://127.0.0.1:3306/emep?useUnicode=true&characterEncoding=utf8
          username: root
          password: root
          # 连接池配置
          initial-size: 5
          min-idle: 5
          max-active: 20
          # 连接等待超时时间
          max-wait: 30000
          # 配置检测可以关闭的空闲连接间隔时间
          time-between-eviction-runs-millis: 60000
          # 配置连接在池中的最小生存时间
          min-evictable-idle-time-millis: 300000
          validation-query: select '1' from dual
          test-while-idle: true
          test-on-borrow: false
          test-on-return: false
          # 打开PSCache,并且指定每个连接上PSCache的大小
          pool-prepared-statements: true
          max-open-prepared-statements: 20
          max-pool-prepared-statement-per-connection-size: 20
          # 配置监控统计拦截的filters, 去掉后监控界面sql无法统计, 'wall'用于防火墙
          filters: stat,wall
          # Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
          aop-patterns: com.springboot.servie.*
          
        
          # WebStatFilter配置
          web-stat-filter:
            enabled: true
            # 添加过滤规则
            url-pattern: /*
            # 忽略过滤的格式
            exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
          
          # StatViewServlet配置 
          stat-view-servlet:
            enabled: true
            # 访问路径为/druid时,跳转到StatViewServlet
            url-pattern: /druid/*
            # 是否能够重置数据
            reset-enable: false
            # 需要账号密码才能访问控制台
            login-username: druid
            login-password: druid
            # IP白名单
            # allow: 127.0.0.1
            # IP黑名单(共同存在时,deny优先于allow)
            # deny: 192.168.1.218
          
          # 配置StatFilter
          filter: 
            stat: 
              log-slow-sql: true
    

    启动项目

    "D:\Program Files\Java\jdk1.8.0_45\bin\java" -XX:TieredStopAtLevel=1 -noverify -Dspring.output.ansi.enabled=always "-javaagent:D:\Program Files\JetBrains\IntelliJ IDEA 2017.1.3\lib\idea_rt.jar=56384:D:\Program Files\JetBrains\IntelliJ IDEA 2017.1.3\bin" -Dfile.encoding=UTF-8 -classpath "D:\Program Files\Java\jdk1.8.0_45\jre\lib\charsets.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\deploy.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\access-bridge-64.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\cldrdata.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\dnsns.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\jaccess.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\jfxrt.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\localedata.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\nashorn.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunec.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunjce_provider.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunmscapi.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\sunpkcs11.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\ext\zipfs.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\javaws.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\jce.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\jfr.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\jfxswt.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\jsse.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\management-agent.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\plugin.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\resources.jar;D:\Program Files\Java\jdk1.8.0_45\jre\lib\rt.jar;D:\git\springboot\target\classes;D:\mavenRepository\org\springframework\boot\spring-boot-starter-web\2.0.4.RELEASE\spring-boot-starter-web-2.0.4.RELEASE.jar;D:\mavenRepository\org\springframework\boot\spring-boot-starter\2.0.4.RELEASE\spring-boot-starter-2.0.4.RELEASE.jar;D:\mavenRepository\org\springframework\boot\spring-boot\2.0.4.RELEASE\spring-boot-2.0.4.RELEASE.jar;D:\mavenRepository\org\springframework\boot\spring-boot-starter-logging\2.0.4.RELEASE\spring-boot-starter-logging-2.0.4.RELEASE.jar;D:\mavenRepository\ch\qos\logback\logback-classic\1.2.3\logback-classic-1.2.3.jar;D:\mavenRepository\ch\qos\logback\logback-core\1.2.3\logback-core-1.2.3.jar;D:\mavenRepository\org\apache\logging\log4j\log4j-to-slf4j\2.10.0\log4j-to-slf4j-2.10.0.jar;D:\mavenRepository\org\apache\logging\log4j\log4j-api\2.10.0\log4j-api-2.10.0.jar;D:\mavenRepository\org\slf4j\jul-to-slf4j\1.7.25\jul-to-slf4j-1.7.25.jar;D:\mavenRepository\javax\annotation\javax.annotation-api\1.3.2\javax.annotation-api-1.3.2.jar;D:\mavenRepository\org\yaml\snakeyaml\1.19\snakeyaml-1.19.jar;D:\mavenRepository\org\springframework\boot\spring-boot-starter-json\2.0.4.RELEASE\spring-boot-starter-json-2.0.4.RELEASE.jar;D:\mavenRepository\com\fasterxml\jackson\core\jackson-databind\2.9.6\jackson-databind-2.9.6.jar;D:\mavenRepository\com\fasterxml\jackson\core\jackson-annotations\2.9.0\jackson-annotations-2.9.0.jar;D:\mavenRepository\com\fasterxml\jackson\core\jackson-core\2.9.6\jackson-core-2.9.6.jar;D:\mavenRepository\com\fasterxml\jackson\datatype\jackson-datatype-jdk8\2.9.6\jackson-datatype-jdk8-2.9.6.jar;D:\mavenRepository\com\fasterxml\jackson\datatype\jackson-datatype-jsr310\2.9.6\jackson-datatype-jsr310-2.9.6.jar;D:\mavenRepository\com\fasterxml\jackson\module\jackson-module-parameter-names\2.9.6\jackson-module-parameter-names-2.9.6.jar;D:\mavenRepository\org\springframework\boot\spring-boot-starter-tomcat\2.0.4.RELEASE\spring-boot-starter-tomcat-2.0.4.RELEASE.jar;D:\mavenRepository\org\apache\tomcat\embed\tomcat-embed-core\8.5.32\tomcat-embed-core-8.5.32.jar;D:\mavenRepository\org\apache\tomcat\embed\tomcat-embed-el\8.5.32\tomcat-embed-el-8.5.32.jar;D:\mavenRepository\org\apache\tomcat\embed\tomcat-embed-websocket\8.5.32\tomcat-embed-websocket-8.5.32.jar;D:\mavenRepository\org\hibernate\validator\hibernate-validator\6.0.11.Final\hibernate-validator-6.0.11.Final.jar;D:\mavenRepository\javax\validation\validation-api\2.0.1.Final\validation-api-2.0.1.Final.jar;D:\mavenRepository\org\jboss\logging\jboss-logging\3.3.2.Final\jboss-logging-3.3.2.Final.jar;D:\mavenRepository\com\fasterxml\classmate\1.3.4\classmate-1.3.4.jar;D:\mavenRepository\org\springframework\spring-web\5.0.8.RELEASE\spring-web-5.0.8.RELEASE.jar;D:\mavenRepository\org\springframework\spring-beans\5.0.8.RELEASE\spring-beans-5.0.8.RELEASE.jar;D:\mavenRepository\org\springframework\spring-webmvc\5.0.8.RELEASE\spring-webmvc-5.0.8.RELEASE.jar;D:\mavenRepository\org\springframework\spring-aop\5.0.8.RELEASE\spring-aop-5.0.8.RELEASE.jar;D:\mavenRepository\org\springframework\spring-context\5.0.8.RELEASE\spring-context-5.0.8.RELEASE.jar;D:\mavenRepository\org\springframework\spring-expression\5.0.8.RELEASE\spring-expression-5.0.8.RELEASE.jar;D:\mavenRepository\org\mybatis\spring\boot\mybatis-spring-boot-starter\1.3.1\mybatis-spring-boot-starter-1.3.1.jar;D:\mavenRepository\org\springframework\boot\spring-boot-starter-jdbc\2.0.4.RELEASE\spring-boot-starter-jdbc-2.0.4.RELEASE.jar;D:\mavenRepository\com\zaxxer\HikariCP\2.7.9\HikariCP-2.7.9.jar;D:\mavenRepository\org\springframework\spring-jdbc\5.0.8.RELEASE\spring-jdbc-5.0.8.RELEASE.jar;D:\mavenRepository\org\springframework\spring-tx\5.0.8.RELEASE\spring-tx-5.0.8.RELEASE.jar;D:\mavenRepository\org\mybatis\spring\boot\mybatis-spring-boot-autoconfigure\1.3.1\mybatis-spring-boot-autoconfigure-1.3.1.jar;D:\mavenRepository\org\mybatis\mybatis\3.4.5\mybatis-3.4.5.jar;D:\mavenRepository\org\mybatis\mybatis-spring\1.3.1\mybatis-spring-1.3.1.jar;D:\mavenRepository\mysql\mysql-connector-java\5.1.46\mysql-connector-java-5.1.46.jar;D:\mavenRepository\com\alibaba\druid-spring-boot-starter\1.1.10\druid-spring-boot-starter-1.1.10.jar;D:\mavenRepository\com\alibaba\druid\1.1.10\druid-1.1.10.jar;D:\mavenRepository\org\slf4j\slf4j-api\1.7.25\slf4j-api-1.7.25.jar;D:\mavenRepository\org\springframework\boot\spring-boot-autoconfigure\2.0.4.RELEASE\spring-boot-autoconfigure-2.0.4.RELEASE.jar;D:\mavenRepository\org\springframework\spring-core\5.0.8.RELEASE\spring-core-5.0.8.RELEASE.jar;D:\mavenRepository\org\springframework\spring-jcl\5.0.8.RELEASE\spring-jcl-5.0.8.RELEASE.jar" com.emep.SpringbootApplication
    
      .   ____          _            __ _ _
     /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
    ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
     \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
      '  |____| .__|_| |_|_| |_\__, | / / / /
     =========|_|==============|___/=/_/_/_/
     :: Spring Boot ::        (v2.0.4.RELEASE)
    
    2019-03-11 23:31:36.334  INFO 18084 --- [           main] com.emep.SpringbootApplication           : Starting SpringbootApplication on 531DD9DWYB33J58 with PID 18084 (D:\git\springboot\target\classes started by Administrator in D:\git\springboot)
    2019-03-11 23:31:36.338  INFO 18084 --- [           main] com.emep.SpringbootApplication           : No active profile set, falling back to default profiles: default
    2019-03-11 23:31:36.401  INFO 18084 --- [           main] ConfigServletWebServerApplicationContext : Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@769f71a9: startup date [Mon Mar 11 23:31:36 CST 2019]; root of context hierarchy
    2019-03-11 23:31:37.491  WARN 18084 --- [           main] o.m.s.mapper.ClassPathMapperScanner      : No MyBatis mapper was found in '[com.emep]' package. Please check your configuration.
    2019-03-11 23:31:37.836  INFO 18084 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'com.alibaba.druid.spring.boot.autoconfigure.stat.DruidSpringAopConfiguration' of type [com.alibaba.druid.spring.boot.autoconfigure.stat.DruidSpringAopConfiguration] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
    2019-03-11 23:31:38.532  INFO 18084 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
    2019-03-11 23:31:38.567  INFO 18084 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
    2019-03-11 23:31:38.567  INFO 18084 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet Engine: Apache Tomcat/8.5.32
    2019-03-11 23:31:38.571  INFO 18084 --- [ost-startStop-1] o.a.catalina.core.AprLifecycleListener   : The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [D:\Program Files\Java\jdk1.8.0_45\bin;C:\windows\Sun\Java\bin;C:\windows\system32;C:\windows;C:\Program Files (x86)\Common Files\NetSarang;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;D:\app\Administrator\product\11.2.0\dbhome_1\bin;C:\ProgramData\Oracle\Java\javapath;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;D:\Program Files\Java\jdk1.8.0_45\bin\;C:\Program Files\MySQL\MySQL Utilities 1.6\;D:\changhon\apache-maven-3.6.0\bin;D:\Program Files\TortoiseGit\bin;D:\Program Files\Git\cmd;D:\Program Files\VisualSVN Server\bin;D:\Program Files\TortoiseSVN\bin;D:\Program Files\nodejs\;C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps;C:\Users\Administrator\AppData\Roaming\npm;C:\Program Files (x86);.]
    2019-03-11 23:31:38.693  INFO 18084 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
    2019-03-11 23:31:38.694  INFO 18084 --- [ost-startStop-1] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 2296 ms
    2019-03-11 23:31:38.830  INFO 18084 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet dispatcherServlet mapped to [/]
    2019-03-11 23:31:38.832  INFO 18084 --- [ost-startStop-1] o.s.b.w.servlet.ServletRegistrationBean  : Servlet statViewServlet mapped to [/druid/*]
    2019-03-11 23:31:38.835  INFO 18084 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'characterEncodingFilter' to: [/*]
    2019-03-11 23:31:38.835  INFO 18084 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
    2019-03-11 23:31:38.836  INFO 18084 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'httpPutFormContentFilter' to: [/*]
    2019-03-11 23:31:38.836  INFO 18084 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'requestContextFilter' to: [/*]
    2019-03-11 23:31:38.836  INFO 18084 --- [ost-startStop-1] o.s.b.w.servlet.FilterRegistrationBean   : Mapping filter: 'webStatFilter' to urls: [/*]
    2019-03-11 23:31:38.967  INFO 18084 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2019-03-11 23:31:39.224  INFO 18084 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@769f71a9: startup date [Mon Mar 11 23:31:36 CST 2019]; root of context hierarchy
    2019-03-11 23:31:39.279  INFO 18084 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/index]}" onto public java.lang.String com.emep.controller.HelloController.index()
    2019-03-11 23:31:39.285  INFO 18084 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
    2019-03-11 23:31:39.286  INFO 18084 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
    2019-03-11 23:31:39.313  INFO 18084 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2019-03-11 23:31:39.313  INFO 18084 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
    2019-03-11 23:31:39.432  INFO 18084 --- [           main] c.a.d.s.b.a.DruidDataSourceAutoConfigure : Init DruidDataSource
    Mon Mar 11 23:31:39 CST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Mon Mar 11 23:31:39 CST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Mon Mar 11 23:31:39 CST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Mon Mar 11 23:31:39 CST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    Mon Mar 11 23:31:39 CST 2019 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.
    2019-03-11 23:31:39.848  INFO 18084 --- [           main] com.alibaba.druid.pool.DruidDataSource   : {dataSource-1} inited
    2019-03-11 23:31:40.308  INFO 18084 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Registering beans for JMX exposure on startup
    2019-03-11 23:31:40.309  INFO 18084 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'statFilter' has been autodetected for JMX exposure
    2019-03-11 23:31:40.310  INFO 18084 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Bean with name 'dataSource' has been autodetected for JMX exposure
    2019-03-11 23:31:40.315  INFO 18084 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'dataSource': registering with JMX server as MBean [com.alibaba.druid.spring.boot.autoconfigure:name=dataSource,type=DruidDataSourceWrapper]
    2019-03-11 23:31:40.316  INFO 18084 --- [           main] o.s.j.e.a.AnnotationMBeanExporter        : Located MBean 'statFilter': registering with JMX server as MBean [com.alibaba.druid.filter.stat:name=statFilter,type=StatFilter]
    2019-03-11 23:31:40.359  INFO 18084 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
    2019-03-11 23:31:40.364  INFO 18084 --- [           main] com.emep.SpringbootApplication           : Started SpringbootApplication in 4.653 seconds (JVM running for 5.355)
    
    

    上述配置不但配置了Druid作为连接池,而且还开启了Druid的监控功能。 其他配置可参考官方wiki——https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

    此时,运行项目,访问http://localhost:8080/druid

    image.png

    输入用户名durid 跟密码druid

    image.png

    我们在请求一次http://localhost:8080/index然后看请求url

    image.png
    5.使用MyBatis

    使用的库表:

    /*
    Navicat MySQL Data Transfer
    
    Source Server         : Mysql
    Source Server Version : 50720
    Source Host           : localhost:3306
    Source Database       : emep
    
    Target Server Type    : MYSQL
    Target Server Version : 50720
    File Encoding         : 65001
    
    Date: 2019-03-11 23:50:42
    */
    
    SET FOREIGN_KEY_CHECKS=0;
    
    -- ----------------------------
    -- Table structure for `student`
    -- ----------------------------
    DROP TABLE IF EXISTS `student`;
    CREATE TABLE `student` (
      `sno` varchar(3) NOT NULL,
      `sname` varchar(9) NOT NULL,
      `ssex` char(2) NOT NULL,
      PRIMARY KEY (`sno`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
    -- ----------------------------
    -- Records of student
    -- ----------------------------
    INSERT INTO `student` VALUES ('001', 'KangKang', 'M');
    INSERT INTO `student` VALUES ('002', 'Mike', 'M');
    INSERT INTO `student` VALUES ('003', 'Jane', 'F');
    
    

    1.创建对应实体:

    package com.emep.vo;
    
    import java.io.Serializable;
    
    /**
     * Created by Administrator on 2019/3/11/011.
     */
    public class Student implements Serializable {
        private static final long serialVersionUID = -339516038496531943L;
        private String sno;
        private String name;
        private String sex;
    
        public String getSno() {
            return sno;
        }
    
        public void setSno(String sno) {
            this.sno = sno;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getSex() {
            return sex;
        }
    
        public void setSex(String sex) {
            this.sex = sex;
        }
    }
    
    

    2.创建一个包含基本CRUD的StudentMapper:

    package com.emep.dao;
    
    import com.emep.vo.Student;
    
    /**
     * Created by Administrator on 2019/3/11/011.
     */
    public interface StudentMapper {
    
        int add(Student student);
        int update(Student student);
        int deleteByIds(String sno);
        Student queryStudentById(Long id);
    }
    

    StudentMapper的实现可以基于xml也可以基于注解。

    6.使用注解方式

    继续编辑StudentMapper:

    @Component
    @Mapper
    public interface StudentMapper {
        @Insert("insert into student(sno,sname,ssex) values(#{sno},#{name},#{sex})")
        int add(Student student);
        
        @Update("update student set sname=#{name},ssex=#{sex} where sno=#{sno}")
        int update(Student student);
        
        @Delete("delete from student where sno=#{sno}")
        int deleteBysno(String sno);
        
        @Select("select * from student where sno=#{sno}")
        @Results(id = "student",value= {
            @Result(property = "sno", column = "sno", javaType = String.class),
            @Result(property = "name", column = "sname", javaType = String.class),
            @Result(property = "sex", column = "ssex", javaType = String.class)
        })
        Student queryStudentBySno(String sno);
    }
    

    简单的语句只需要使用@Insert、@Update、@Delete、@Select这4个注解即可,动态SQL语句需要使用@InsertProvider、@UpdateProvider、@DeleteProvider、@SelectProvider等注解。具体可参考MyBatis官方文档:http://www.mybatis.org/mybatis-3/zh/java-api.html

    7.使用xml方式

    使用xml方式需要在application.yml中进行一些额外的配置:

    mybatis:
      # type-aliases扫描路径
      # type-aliases-package:
      # mapper xml实现扫描路径
      mapper-locations: classpath:mapper/*.xml
      property:
        order: BEFORE
    
    8.业务层

    接下来编写Service:

    public interface StudentService {
        int add(Student student);
        int update(Student student);
        int deleteBysno(String sno);
        Student queryStudentBySno(String sno);
    }
    

    实现类:

    @Service("studentService")
    public class StudentServiceImp implements StudentService{
        @Autowired
        private StudentMapper studentMapper;
        
        @Override
        public int add(Student student) {
            return this.studentMapper.add(student);
        }
        
        @Override
        public int update(Student student) {
            return this.studentMapper.update(student);
        }
        
        @Override
        public int deleteBysno(String sno) {
            return this.studentMapper.deleteBysno(sno);
        }
        
        @Override
        public Student queryStudentBySno(String sno) {
            return this.studentMapper.queryStudentBySno(sno);
        }
    }
    

    编写controller:

    @RestController
    public class TestController {
    
        @Autowired
        private StudentService studentService;
        
        @RequestMapping( value = "/querystudent", method = RequestMethod.GET)
        public Student queryStudentBySno(String sno) {
            return this.studentService.queryStudentBySno(sno);
        }
    }
    

    完整的项目目录如下图所示:


    image.png

    查看请求


    image.png

    查看请求


    image.png

    查看SQL监控情况:


    image.png

    * 本文作者: BYP

    相关文章

      网友评论

          本文标题:Spring Boot整合Mybatis

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