springboot整合mybatis

Posted 小蜜疯

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot整合mybatis相关的知识,希望对你有一定的参考价值。

1、springboot配置数据库连接池druid

2、springboot整合mybatis

3、springboot整合pagehelper

 

 

springboot配置数据库连接池druid

 

新建springboot项目

 

 

 

相关pom依赖

druid所需pom依赖

 

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid-spring-boot-starter</artifactId>
     <version>1.1.10</version>
  </dependency>

 

 

配置application.yml

spring:
 datasource:
    #1.JDBC
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/book?useUnicode=true&characterEncoding=utf8
    username: root
    password: 123
    druid:
       #2.连接池配置
      #初始化连接池的连接数量 大小,最小,最大
      initial-size: 5
      min-idle: 5
      max-active: 20
      #配置获取连接等待超时的时间
      max-wait: 60000
        #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
      time-between-eviction-runs-millis: 60000
      # 配置一个连接在池中最小生存的时间,单位是毫秒
      min-evictable-idle-time-millis: 30000
      validation-query: SELECT 1 FROM DUAL
      test-while-idle: true
      test-on-borrow: true
      test-on-return: false
      # 是否缓存preparedStatement,也就是PSCache  官方建议MySQL下建议关闭   个人建议如果想用SQL防火墙 建议打开
      pool-prepared-statements: true
      max-pool-prepared-statement-per-connection-size: 20
     # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,\'wall\'用于防火墙
      filter:
        stat:
          merge-sql: true
          slow-sql-millis: 5000
      #3.基础监控配置
      web-stat-filter:
        enabled: true
        url-pattern: /*
        #设置不统计哪些URL
        exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
        session-stat-enable: true
        session-stat-max-count: 100
      stat-view-servlet:
        enabled: true
        url-pattern: /druid/*
        reset-enable: true
        #设置监控页面的登录名和密码
        login-username: admin
        login-password: admin
        allow: 127.0.0.1

springboot整合druid成功截图

启动SpringBoot项目访问druid  http://localhost:tomcat端口号/项目名称/druid/

 

 

 

 

 

 

 

 

 

 

 用户名和密码在配置里面

 

 

成功登陆会出现该界面

 

 

 

 

 

 

 

 

springboot整合mybatis

 

springboot整合mybatis逆向生成插件

相关pom依赖

<!--更改springboot中的mysql版本,逆向生成不兼容高版本-->
<mysql.version>5.1.44</mysql.version>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>${mysql.version}</version>
    <scope>runtime</scope>
</dependency>

<resources>
    <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
    <resource>
        <directory>src/main/java</directory>
        <includes>
            <include>**/*.xml</include>
        </includes>
    </resource>
    <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
    <resource>
        <directory>src/main/resources</directory>
        <includes>
            <include>*.properties</include>
            <include>*.xml</include>
            <include>*.yml</include>
        </includes>
    </resource>
</resources>

<plugin>
    <groupId>org.mybatis.generator</groupId>
    <artifactId>mybatis-generator-maven-plugin</artifactId>
    <version>1.3.2</version>
    <dependencies>
        <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
    </dependencies>
    <configuration>
        <overwrite>true</overwrite>
    </configuration>
</plugin>

逆向生成配置文件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" >
<generatorConfiguration>
    <!-- 引入配置文件 -->
    <properties resource="jdbc.properties"/>

    <!--指定数据库jdbc驱动jar包的位置-->
    <classPathEntry location="D:\\repository\\mvn-repository\\mysql\\mysql-connector-java\\5.1.44\\mysql-connector-java-5.1.44.jar"/>
    <!-- 一个数据库一个context -->
    <context id="infoGuardian">
        <!-- 注释 -->
        <commentGenerator>
            <property name="suppressAllComments" value="true"/><!-- 是否取消注释 -->
            <property name="suppressDate" value="true"/> <!-- 是否生成注释代时间戳 -->
        </commentGenerator>

        <!-- jdbc连接 -->
        <jdbcConnection driverClass="${jdbc.driver}"
                        connectionURL="${jdbc.url}" userId="${jdbc.username}" password="${jdbc.password}"/>

        <!-- 类型转换 -->
        <javaTypeResolver>
            <!-- 是否使用bigDecimal, false可自动转化以下类型(Long, Integer, Short, etc.) -->
            <property name="forceBigDecimals" value="false"/>
        </javaTypeResolver>

        <!-- 01 指定javaBean生成的位置 -->
        <!-- targetPackage:指定生成的model生成所在的包名 -->
        <!-- targetProject:指定在该项目下所在的路径  -->
        <javaModelGenerator targetPackage="com.hmc.springboot02.model"
                            targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
            <!-- 是否对model添加构造函数 -->
            <property name="constructorBased" value="true"/>
            <!-- 是否针对string类型的字段在set的时候进行trim调用 -->
            <property name="trimStrings" value="false"/>
            <!-- 建立的Model对象是否 不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
            <property name="immutable" value="false"/>
        </javaModelGenerator>

        <!-- 02 指定sql映射文件生成的位置 -->
        <sqlMapGenerator targetPackage="com.hmc.springboot02.mapper"
                         targetProject="src/main/java">
            <!-- 是否允许子包,即targetPackage.schemaName.tableName -->
            <property name="enableSubPackages" value="false"/>
        </sqlMapGenerator>

        <!-- 03 生成XxxMapper接口 -->
        <!-- type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象 -->
        <!-- type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象 -->
        <!-- type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口 -->
        <javaClientGenerator targetPackage="com.hmc.springboot02.mapper"
                             targetProject="src/main/java" type="XMLMAPPER">
            <!-- 是否在当前路径下新加一层schema,false路径com.oop.eksp.user.model, true:com.oop.eksp.user.model.[schemaName] -->
            <property name="enableSubPackages" value="false"/>
        </javaClientGenerator>

        <!-- 配置表信息 -->
        <!-- schema即为数据库名 -->
        <!-- tableName为对应的数据库表 -->
        <!-- domainObjectName是要生成的实体类 -->
        <!-- enable*ByExample是否生成 example类 -->
        <!--<table schema="" tableName="t_book" domainObjectName="Book"-->
               <!--enableCountByExample="false" enableDeleteByExample="false"-->
               <!--enableSelectByExample="false" enableUpdateByExample="false">-->
            <!--&lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;-->
            <!--&lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;-->
            <!--&lt;!&ndash; 指定列的java数据类型 &ndash;&gt;-->
            <!--&lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;-->
        <!--</table>-->

        <!--<table schema="" tableName="t_mvc_book" domainObjectName="MvcBook"
               enableCountByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" enableUpdateByExample="false">
            &lt;!&ndash; 忽略列,不生成bean 字段 &ndash;&gt;
            &lt;!&ndash; <ignoreColumn column="FRED" /> &ndash;&gt;
            &lt;!&ndash; 指定列的java数据类型 &ndash;&gt;
            &lt;!&ndash; <columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" /> &ndash;&gt;
        </table>-->

    </context>
</generatorConfiguration>

 

 

 

逆向生成集成到maven中的命令

 

 

 

 

 

springboot整合mybatis

使用@Repository注解,在启动类中添加@MapperScan(“xxxx”)注解,用于扫描Mapper类的包。扫描多个包:@MapperScan({”com.javaxl.springboot02.dao”,”com.javaxl.springboot02.entity”})

 //启用事物管理器

  @EnableTransactionManagement

package com.hmc.springboot02;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
//开启Maooer自动扫描
@MapperScan("com.hmc.*.mapper")
//开启事务管理器
@EnableTransactionManagement
////开启动态代理
@EnableAspectJAutoProxy
public class Springboot02Application {
    public static void main(String[] args) {
        SpringApplication.run(Springboot02Application.class, args);
    }

}

 

 

  

springboot整合pagehelper

导入相关pom依赖

<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

配置application.yml文件

#pagehelper插件
pagehelper:
    helperDialect: mysql
    reasonable: true
    supportMethodsArguments: true
    params: count=countSql

 

 

 

PagerAspect.java

package com.hmc.springboot02.util;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Aspect
public class PageAspect {

    @Around("execution(* *..*Service.*Pager(..))")
    public Object invoke(ProceedingJoinPoint args) throws Throwable{
        Object[] params = args.getArgs();
        PageBean pageBean=null;
        for (Object param : params) {
            if(param instanceof PageBean){
                pageBean=(PageBean) param;
                break;
            }
        }

        if(null!=pageBean&&pageBean.isPagination())
            PageHelper.startPage(pageBean.getPage(),pageBean.getRows());

        Object result = args.proceed(params);

        if(null!=pageBean&&pageBean.isPagination()){
            List lst=(List)result;
            PageInfo pageInfo=new PageInfo(lst);
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return result;
    }
}

 

MvcBookMapper
package com.hmc.springboot02.mapper;

import com.hmc.springboot02.model.MvcBook;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Repository
public interface MvcBookMapper {
    /**
     * 分页查询书本信息
     * @param mvcBook
     * @return
     */
    List<MvcBook> queryBookPager(MvcBook mvcBook);

    MvcBook queryMvcbook(Integer id);


}

MvcBookMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.hmc.springboot02.mapper.MvcBookMapper" >
  <resultMap id="BaseResultMap" type="com.hmc.springboot02.model.MvcBook" >
    <constructor >
      <arg column="bid" jdbcType="INTEGER" javaType="java.lang.Integer" />
      <arg column="bname" jdbcType="VARCHAR" javaType="java.lang.String" />
      <arg column="price" jdbcType="REAL" javaType="java.lang.Float" />
      <arg column="image" jdbcType="VARCHAR" javaType="java.lang.String" />
    </constructor>
  </resultMap>

  <select id="queryBookPager" resultType="com.hmc.springboot02.model.MvcBook"
          parameterType="com.hmc.springboot02.model.MvcBook">
     select * from t_mvc_book where 1=1
  <if test="null!=bname and \'\'!=bname">
   and bname like concat(concat(\'%\',#{bname}),\'%\')
  </if>
  </select>

    <select id="queryMvcbook" resultType="com.hmc.springboot02.model.MvcBook">
     SELECT  * from   t_mvc_book where bid=#{id}
        </select>


</mapper>
IMvcBookService
package com.hmc.springboot02.service;

import com.hmc.springboot02.model.MvcBook;
import com.hmc.springboot02.util.PageBean;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


public interface IMvcBookService {
    /**
     * 分页查询书本信息
     * @param mvcBook
     * @return
     */
    @Transactional(readOnly = true)
    List<MvcBook> queryBookPager(MvcBook mvcBook, PageBean PageBean);

    MvcBook queryMvcbook(Integer id);

    void clear();
}
MvcBookServiceImpl
package com.hmc.springboot02.service.impl;

import com.hmc.springboot02.mapper.MvcBookMapper;
import com.hmc.springboot02.model.MvcBook;
import com.hmc.springboot02.service.IMvcBookService;
import com.hmc.springboot02.util.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author胡明财
 * @site www.xiaomage.com
 * @company xxx公司
 * @create  2019-11-24 20:38
 */
@Service
public class MvcBookServiceImpl implements IMvcBookService {
   @Autowired
   private MvcBookMapper MvcBookMapper;


    
    @Override
    public List<MvcBook> queryBookPager(MvcBook mvcBook, PageBean PageBean) {
        return MvcBookMapper.queryBookPager(mvcBook);
    }



    @Override
    public MvcBook queryMvcbook(Integer id) {
        return MvcBookMapper.queryMvcbook(id);
    }

   
  

}

 

测试代码如下

package com.hmc.springboot02.service.impl;

import com.hmc.springboot02.Springboot02Application;
import com.hmc.springboot02.model.MvcBook;
import com.hmc.springboot02.service.IMvcBookService;
import com.hmc.springboot02.util.PageBean;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import static org.junit.jupiter.api.Assertions.*;

/**
 * @author胡明财
 * @site www.xiaomage.com
 * @company xxx公司
 * @create  2019-11-24 21:12
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes ={Springboot02Application.class})
class MvcBookServiceImplTest {

    @Autowired
    private IMvcBookService IMvcBookService;
    private MvcBook MvcBook;
    @BeforeEach
    void setUp() {
        MvcBook=new MvcBook();
    }

    @Test
    void queryBookPager() {
        PageBean pageBean=new PageBean();
        List<MvcBook> mvcBooks = IMvcBookService.queryBookPager(MvcBook, pageBean);
        for (MvcBook mvcBook : mvcBooks) {
             System.out.println(mvcBook);
        }
    }

    @Test
    void queryBook() {
        MvcBook mvcBook = IMvcBookService.queryMvcbook(568);
        System.out.println(mvcBook);

    }

    @Test
    void queryBoo() {
       IMvcBookService.clear();
    }
}

 

 

 

开始测试

 

 

 测试单个

 

 

 

 

以上是关于springboot整合mybatis的主要内容,如果未能解决你的问题,请参考以下文章

springboot整合mybatis,redis,代码

SpringBoot系列Mybatis整合

SpringBoot系列Mybatis整合

springboot整合mybatis开发

18.springboot整合mybatis

SpringBoot:4.SpringBoot整合Mybatis实现数据库访问