• 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏吧

SpringBoot配置数据库连接池druid、整合mybatis和pagehelper

java 来源:贝贝睡不饱 2次浏览

SpringBoot

SpringBoot配置数据库连接池druid

首先创建springboot工程

导入相关pom依赖

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

减低版本避免没必要的错误
pom.xml

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.myy</groupId>
    <artifactId>springboot02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot02</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <mysql.version>5.1.44</mysql.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

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

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

配置application.yml
application.yml配置devtools热加载(因为我idea有配置热加载所以我就没有代码配置了)

spring
  #devtools热加载
  devtools:
    restart:
      #启用热加载
      enabled: true
      #添加那个目录的文件不需要restart
      exclude: static/*
      #添加那个目录的文件需要restart
      additional-paths: src/main/java

application.yml配置druid
springboot默认数据源是org.apache.tomcat.jdbc.pool.DataSource

server:
  port: 80
  servlet:
    context-path: /
spring:
  datasource:
    #1.JDBC
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/db_xm?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
    username: root
    password: 123456
    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
        #deny: 192.168.1.100

监控平台并不是被所有的电脑访问,allow是该项目只能被本机访问

测试代码

package com.myy.springboot02.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/** * @author 熊贝贝 * @site www.myy.com * @company * @create 2019-12-28 20:28 */
@RestController
@RequestMapping("/demo")
public class HelloController { 

    @RequestMapping("/say1")
    public String say1(){ 
        return "说活1";
    }

    @RequestMapping("/say2")
    public String say2(){ 
        try { 
            Thread.sleep(2000);
        } catch (InterruptedException e) { 
            e.printStackTrace();
        }
        return "说活2";
    }

    @RequestMapping("/say3")
    public String say3(){ 
        try { 
            Thread.sleep(5000);
        } catch (InterruptedException e) { 
            e.printStackTrace();
        }
        return "说活3";
    }

}

springboot整合druid成功截图
启动SpringBoot项目访问druid, http://localhost:tomcat端口号/项目名称/druid/


相当于c3p0
①监控sql的执行效率
②监控url的响应时长

SpringBoot整合mybatis

相关pom依赖

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.2.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.myy</groupId>
    <artifactId>springboot02</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>springboot02</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <mysql.version>5.1.44</mysql.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

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

    </dependencies>

    <build>
        <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>

        <plugins>
            <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>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

逆向生成配置文件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:\\intPath\\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.myy.springboot02.entity" 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.myy.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.myy.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_mvc_book" domainObjectName="Book" enableCountByExample="false" enableDeleteByExample="false" enableSelectByExample="false" enableUpdateByExample="false">
            <property name="useActualColumnNames" value="true" />
        </table>


    </context>
</generatorConfiguration>

运行完记得切换,否则再次运行会覆盖写的代码
逆向生成集成到maven中的命令
mybatis-generator:generate -e

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_xm?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

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

package com.myy.springboot02;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@MapperScan("com.myy.springboot02.mapper")
@SpringBootApplication
public class Springboot02Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot02Application.class, args);
    }

}

BookMapper加上注解@Repository
Service层

package com.myy.springboot02.service;

import com.myy.springboot02.entity.Book;

/**
 * @author 熊贝贝
 * @site www.myy.com
 * @company
 * @create  2019-12-29 19:20
 */
public interface BookService {
    int deleteByPrimaryKey(Integer bid);

    Book selectByPrimaryKey(Integer bid);

}

package com.myy.springboot02.service.impl;

import com.myy.springboot02.entity.Book;
import com.myy.springboot02.mapper.BookMapper;
import com.myy.springboot02.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author 熊贝贝
 * @site www.myy.com
 * @company
 * @create  2019-12-29 19:21
 */

@Service
public class BookServiceImpl implements BookService {
    @Autowired
    private BookMapper bookMapper;

    @Override
    public int deleteByPrimaryKey(Integer bid) {
        return bookMapper.deleteByPrimaryKey(bid);
    }

    @Override
    public Book selectByPrimaryKey(Integer bid) {
        return bookMapper.selectByPrimaryKey(bid);
    }
}

代码测试
需要用到pom依赖

<junit.version>4.12</junit.version>

<!--5.其他-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
        </dependency>

Springboot02ApplicationTests.java

package com.myy.springboot02;

import com.myy.springboot02.service.BookService;
import org.junit.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;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = Springboot02Application.class)
public class Springboot02ApplicationTests { 
    @Autowired
    private BookService bookService;

    @Test
   public void select() { 
        System.out.println(this.bookService.selectByPrimaryKey(13));
    }

    @Test
    public void del() { 
        this.bookService.deleteByPrimaryKey(13);
    }

}

表数据:

运行查询测试方法,要看打印效果,得去实体类加上toString
可加注解@ToSTring
如果出现警告: Runner org.junit.internal.runners.ErrorReportingRunner (used on class cn.star.MybatisTest) does可参考这篇博客

代码运行结果
select

del

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

#显示日志
logging:
  level:
    com.myy.springboot02.mapper: debug

相关代码
切面PagerAspect

package com.myy.springboot02.aop;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.myy.springboot02.utils.PageBean;
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;

/** * @author 熊贝贝 * @site www.myy.com * @company * @create 2019-11-18 16:47 * 定义成spring管理的主键 * 定义成切面 */
@Component
@Aspect
public class PagerAspect { 
    // 加入环绕通知
    @Around("execution(* *..*Service.*Pager(..))")
    public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable { 
// 获取目标对象方法的参数集合
        Object[] args = joinPoint.getArgs();
        PageBean pageBean = null;
        for (Object arg : args) { 
            if(arg instanceof PageBean){ 
                pageBean = (PageBean) arg;
                break;
            }
        }
      if(pageBean !=null && pageBean.isPagination()){ 
          PageHelper.startPage(pageBean.getPage(),pageBean.getRows());
      }
// 目标执行
        Object proceed = joinPoint.proceed(args);
// 返回之前做处理
        if(pageBean!=null && pageBean.isPagination()){ 
            PageInfo pageInfo = new PageInfo((List) proceed);
            pageBean.setTotal(pageInfo.getTotal()+"");
        }
        return proceed;
    }
}

分页需要用的工具类
PageBean

package com.myy.springboot02.utils;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;


/** * 分页工具类 * */
public class PageBean { 

	private int page = 1;// 页码

	private int rows = 10;// 页大小

	private int total = 0;// 总记录数

	// 保留上一次的请求地址
	private String url;
	// 保留上一次请求所携带的参数
	private Map<String, String[]> paMap = new HashMap<>();

	/** * pageBean初始化 * @param req */
	public void setRequest(HttpServletRequest req) { 
		//改变它第几页的数据
		this.setPage(req.getParameter("page"));
		//改变它每页展示的数据
		this.setRows(req.getParameter("rows"));
		//控制页面是否分页
		this.setPagination(req.getParameter("pagination"));

		this.setUrl(req.getRequestURL().toString());
		this.setPaMap(req.getParameterMap());
	}

	public void setPagination(String parameter) { 
// 当你填false就不分页
		if("false".equals(pagination)) { 
			this.setPagination(false);
		}
	}

	public void setRows(String rows) { 
		if(StringUtils.isNotBlank(rows)) { 
			this.setRows(Integer.valueOf(rows));
		}
	}

	public void setPage(String page) { 
// 如果不为空的时候
		if(StringUtils.isNotBlank(page)){ 
			this.setPage(Integer.valueOf(page));
		}
	}

	public String getUrl() { 
		return url;
	}

	public void setUrl(String url) { 
		this.url = url;
	}


	public Map<String, String[]> getPaMap() { 
		return paMap;
	}

	public void setPaMap(Map<String, String[]> paMap) { 
		this.paMap = paMap;
	}


	private boolean pagination = true;// 是否分页

	public PageBean() { 
		super();
	}

	public int getPage() { 
		return page;
	}

	public void setPage(int page) { 
		this.page = page;
	}

	public int getRows() { 
		return rows;
	}

	public void setRows(int rows) { 
		this.rows = rows;
	}

	public int getTotal() { 
		return total;
	}

	public void setTotal(int total) { 
		this.total = total;
	}

	public void setTotal(String total) { 
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() { 
		return pagination;
	}

	public void setPagination(boolean pagination) { 
		this.pagination = pagination;
	}

	/** * 获得起始记录的下标 * * @return */
	public int getStartIndex() { 
		return (this.page - 1) * this.rows;
	}

	@Override
	public String toString() { 
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
	}

	/** * 最大页码 * @return */
	public int getMaxPage() { 
		return this.total % this.rows == 0 ? this.total/this.rows : this.total/this.rows + 1;
	}


	/** * 获取下一页 * @return */
	public int getNextPage() { 
		return this.page < this.getMaxPage() ? this.page+1 : this.page;
	}

	/** * 上一页 * @return */
	public int getPreviousPage() { 

		return this.page > 1 ? this.page-1 : this.page;
	}

}

StringUtils

package com.myy.springboot02.utils;

public class StringUtils {
	// 私有的构造方法,保护此类不能在外部实例化
	private StringUtils() {
	}

	/**
	 * 如果字符串等于null或去空格后等于"",则返回true,否则返回false
	 *
	 * @param s
	 * @return
	 */
	public static boolean isBlank(String s) {
		boolean b = false;
		if (null == s || s.trim().equals("")) {
			b = true;
		}
		return b;
	}

	/**
	 * 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
	 *
	 * @param s
	 * @return
	 */
	public static boolean isNotBlank(String s) {
		return !isBlank(s);
	}

}


去启动类中开启动态代理@EnableAspectJAutoProxy
最好开启事务@EnableTransactionManagement,因为有可能Service层会操作两个sql语句
Springboot02Application

package com.myy.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;

@MapperScan("com.myy.springboot02.mapper")
@EnableTransactionManagement
@EnableAspectJAutoProxy
@SpringBootApplication
public class Springboot02Application {

    public static void main(String[] args) {
        SpringApplication.run(Springboot02Application.class, args);
    }

}

BookMapper

List<Book> queryBooksPager(Book book);

BookMapper.xml

<select id="queryBooksPager" resultType="com.myy.springboot02.entity.Book" parameterType="com.myy.springboot02.entity.Book">
    select
    <include refid="Base_Column_List" />
    from t_mvc_book
    <where>
      <if test="bname != null and bname !=''">
        bname like #{bname}
      </if>
    </where>

  </select>

BookService

 List<Book> queryBooksPager(Book book, PageBean pageBean);

BookServiceImpl

@Override
    public List<Book> queryBooksPager(Book book, PageBean pageBean) { 
        return bookMapper.queryBooksPager(book);
    }

代码测试
Springboot02ApplicationTests

 @Test
    public void queryBooksPager() {
        Book book = new Book();
        book.setBname("%圣墟%");
        PageBean pageBean = new PageBean();
        for (Book b : this.bookService.queryBooksPager(book,pageBean)){
            System.out.println(b);
        }
    }

运行结果


版权声明:本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系管理员进行删除。
喜欢 (0)