您的位置:首页 > 编程语言 > Java开发

springboot 2.0 集成mybatis,mybatis-generator,pagehelper

2019-01-22 20:09 633 查看

开发工具idea

springboot 2.0.8

一、pom.xml

[code]<?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>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.urthink.upfs</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mybatis</name>
<description>springboot-mybatis project for Spring Boot</description>

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

<dependencies>
<!--去掉springboot本身日志依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>

<!--log4j2-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

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

<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-core</artifactId>
<version>1.3.7</version>
</dependency>

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

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.7</version>
<configuration>
<!-- mybatis用于生成代码的配置文件 -->
<configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>

<resources>
<resource>
<directory>src/main/resources</directory>
<!-- <excludes>
<exclude>**/*.properties</exclude>
<exclude>**/*.xml</exclude>
</excludes> -->
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
<include>**/*.yml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>

</project>

二、application.yml

[code]server:
port: 8080

spring:
application:
name: springboot-mybatis
datasource:
name: dataSource1 #如果存在多个数据源,监控的时候可以通过名字来区分开来。如果没有配置,将会生成一个名字,格式是:"DataSource-" + System.identityHashCode(this)
type: com.alibaba.druid.pool.DruidDataSource
#druid相关配置
druid:
#监控统计拦截的filters
filters: stat,wall
driver-class-name: com.mysql.jdbc.Driver
#基本属性
url: jdbc:mysql://127.0.0.1:3306/mytest?useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true&useSSL=false
username: root
password: root
#配置初始化大小/最小/最大
initial-size: 1
min-idle: 1
max-active: 20
#获取连接等待超时时间
max-wait: 60000
#间隔多久进行一次检测,检测需要关闭的空闲连接
time-between-eviction-runs-millis: 60000
#一个连接在池中最小生存的时间
min-evictable-idle-time-millis: 30000
validation-query: SELECT 'x'
test-while-idle: true
test-on-borrow: false
test-on-return: false
#打开PSCache,并指定每个连接上PSCache的大小。oracle设为true,mysql设为false。分库分表较多推荐设置为false
pool-prepared-statements: false
max-pool-prepared-statement-per-connection-size: 20

mybatis:
mapper-locations: classpath*:mapper/*.xml,classpath*:**/*Mapper.xml
type-aliases-package: com.urthink.upfs.springbootmybatis.model
configuration:
#进行自动映射时,数据以下划线命名,如数据库返回的"order_address"命名字段是否映射为class的"orderAddress"字段。默认为false
map-underscore-to-camel-case: true
# 输出SQL执行语句 (log4j2本身可以输出sql语句)
#log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #这种带结果集

pagehelper:
helper-dialect: mysql
offset-as-page-num: true
row-bounds-with-count: true #使用RowBounds分页,需要设置为true
#page-size-zero: false
reasonable: true
#params: pageNum=pageNum;pageSize=pageSize;count=countSql;reasonable=reasonable;pageSizeZero=pageSizeZero
#support-methods-arguments: false
#auto-runtime-dialect: false
#close-conn: false
#aggregate-functions:

三、log4j2.xml

[code]<?xml version="1.0" encoding="UTF-8"?>
<!--设置log4j2的自身log级别为warn-->
<!--日志级别以及优先级排序: OFF > FATAL > ERROR > WARN > INFO > DEBUG > TRACE > ALL -->
<!--Configuration后面的status,这个用于设置log4j2自身内部的信息输出,可以不设置,
当设置成trace时,你会看到log4j2内部各种详细输出-->
<!--monitorInterval:Log4j能够自动检测修改配置 文件和重新配置本身,设置间隔秒数-->
<configuration status="warn" monitorInterval="30">
<!--先定义所有的appender-->
<appenders>
<!--这个输出控制台的配置-->
<console name="Console" target="SYSTEM_OUT">
<!--输出日志的格式-->
<PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
</console>
<!--文件会打印出所有信息,这个log每次运行程序会自动清空,由append属性决定,这个也挺有用的,适合临时测试用-->
<File name="log" fileName="logs/test.log" append="false">
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
</File>
<!-- 这个会打印出所有的info及以下级别的信息,每次大小超过size,
则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFileInfo" fileName="logs/info.log"
filePattern="logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
<Filters>
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="INFO" onMatch="ACCEPT" onMismatch="DENY"/>
<ThresholdFilter level="WARN" onMatch="DENY" onMismatch="NEUTRAL"/>
</Filters>
<PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了24 -->
<DefaultRolloverStrategy max="24"/>
</RollingFile>

<RollingFile name="RollingFileWarn" fileName="logs/warn.log"
filePattern="logs/$${date:yyyy-MM}/warn-%d{yyyy-MM-dd}-%i.log">
<Filters>
<ThresholdFilter level="WARN" onMatch="ACCEPT" onMismatch="DENY"/>
<ThresholdFilter level="ERROR" onMatch="DENY" onMismatch="NEUTRAL"/>
</Filters>
<PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了24 -->
<DefaultRolloverStrategy max="24"/>
</RollingFile>

<RollingFile name="RollingFileError" fileName="logs/error.log"
filePattern="logs/$${date:yyyy-MM}/error-%d{yyyy-MM-dd}-%i.log">
<ThresholdFilter level="ERROR"/>
<PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
<Policies>
<TimeBasedTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="100 MB"/>
</Policies>
<!-- DefaultRolloverStrategy属性如不设置,则默认为最多同一文件夹下7个文件,这里设置了24 -->
<DefaultRolloverStrategy max="24"/>
</RollingFile>

</appenders>
<!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
<loggers>
<!--过滤掉spring和hibernate的一些无用的debug信息-->
<logger name="org.springframework" level="INFO">
</logger>
<logger name="org.mybatis" level="INFO">
</logger>

<root level="DEBUG">
<appender-ref ref="Console"/>
<appender-ref ref="RollingFileInfo"/>
<appender-ref ref="RollingFileWarn"/>
<appender-ref ref="RollingFileError"/>
</root>
</loggers>

</configuration>

四、SpringbootMybatisApplication.java

[code]package com.urthink.upfs.springbootmybatis;

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

/**
* springboot-mybatis测试
* @author zhao
* @date 2019.1.22
*/
@SpringBootApplication
@MapperScan("com.urthink.upfs.springbootmybatis")
public class SpringbootMybatisApplication {

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

}

五、generatorConfig.xml

[code]<?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:/Program Files/apache-maven-3.2.5/repository/mysql/mysql-connector-java/5.1.41/mysql-connector-java-5.1.41.jar"/>
<context id="MySQLTables" targetRuntime="MyBatis3">
<property name="beginningDelimiter" value="`"/>
<property name="endingDelimiter" value="`"/>
<property name="mergeable" value="false"></property>
<!-- 文件编码 -->
<property name="javaFileEncoding" value="UTF-8"/>
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost/mytest?useUnicode=true&amp;characterEncoding=UTF-8&amp;allowMultiQueries=true&amp;useSSL=false" userId="root" password="root"></jdbcConnection>
<!-- 非必需,类型处理器,在数据库类型和java类型之间的转换控制-->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>

<!-- Model模型生成器,用来生成含有主键key的类,记录类 以及查询Example类
targetPackage     指定生成的model生成所在的包名
targetProject     指定在该项目下所在的路径
-->
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="com.urthink.upfs.springbootmybatis.entity" targetProject="./src/main/java">
<!-- 是否允许子包,即targetPackage.schemaName.tableName -->
<property name="enableSubPackages" value="true"/>
<!-- 是否对model添加 构造函数 -->
<property name="constructorBased" value="false"/>
<!-- 是否对类CHAR类型的列的数据进行trim操作 -->
<property name="trimStrings" value="true"/>
<!-- 建立的Model对象是否不可改变  即生成的Model对象不会有 setter方法,只有构造方法 -->
<property name="immutable" value="false"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="com.urthink.upfs.springbootmybatis.mapper" targetProject="./src/main/java">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>

<!-- 客户端代码,生成易于使用的针对Model对象和XML配置文件 的代码
type="ANNOTATEDMAPPER",生成Java Model 和基于注解的Mapper对象
type="MIXEDMAPPER",生成基于注解的Java Model 和相应的Mapper对象
type="XMLMAPPER",生成SQLMap XML文件和独立的Mapper接口
-->
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="com.urthink.upfs.springbootmybatis.dao" targetProject="./src/main/java">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成哪些表-->
<!--<table schema="" tableName="sys_organization" domainObjectName="Organization" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false">
<columnOverride column="???" property="???" />
</table>-->

<table schema="" tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>

</context>
</generatorConfiguration>

idea,双击运行

六、建表脚本sql

[code]/*
Navicat Premium Data Transfer

Source Server         : localhost
Source Server Type    : MySQL
Source Server Version : 50724
Source Host           : localhost:3306
Source Schema         : mytest

Target Server Type    : MySQL
Target Server Version : 50724
File Encoding         : 65001

Date: 22/01/2019 19:58:34
*/

SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user`  (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`user_name` varchar(64) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '用户名',
`password` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '密码',
`mobile` varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '手机号',
`enable` char(1) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '是否启用',
`create_by` int(11) NOT NULL COMMENT '创建人',
`create_time` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP(0) COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1017 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES (1000, 'admin', 'xujiami', '13688888888', '1', 1, '2019-01-22 19:58:16');
INSERT INTO `t_user` VALUES (1001, 'test1', 'test', NULL, '1', 1, '2019-01-22 11:13:28');
INSERT INTO `t_user` VALUES (1002, 'test2', 'test', NULL, '1', 1, '2019-01-22 11:18:12');
INSERT INTO `t_user` VALUES (1003, 'test3', 'test', NULL, '1', 1, '2019-01-22 11:18:13');
INSERT INTO `t_user` VALUES (1004, 'test4', 'test', NULL, '1', 1, '2019-01-22 11:18:15');
INSERT INTO `t_user` VALUES (1005, 'test5', 'test', NULL, '1', 1, '2019-01-22 11:18:17');
INSERT INTO `t_user` VALUES (1006, 'test6', 'test', NULL, '1', 1, '2019-01-22 11:18:18');
INSERT INTO `t_user` VALUES (1007, 'test7', 'test', NULL, '1', 1, '2019-01-22 11:18:20');
INSERT INTO `t_user` VALUES (1008, 'test8', 'test', NULL, '1', 1, '2019-01-22 11:18:22');
INSERT INTO `t_user` VALUES (1009, 'test9', 'test', NULL, '1', 1, '2019-01-22 11:18:24');
INSERT INTO `t_user` VALUES (1010, 'test10', 'test', NULL, '1', 1, '2019-01-22 11:18:27');
INSERT INTO `t_user` VALUES (1011, 'test11', 'test', NULL, '1', 1, '2019-01-22 11:18:36');
INSERT INTO `t_user` VALUES (1012, 'test12', 'test', NULL, '1', 1, '2019-01-22 19:56:52');

SET FOREIGN_KEY_CHECKS = 1;

七、实体类

[code]package com.urthink.upfs.springbootmybatis.entity;

import java.util.Date;

public class User {
private Integer id;

private String userName;

private String password;

private String mobile;

private String enable;

private Integer createBy;

private Date createTime;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}

public String getMobile() {
return mobile;
}

public void setMobile(String mobile) {
this.mobile = mobile == null ? null : mobile.trim();
}

public String getEnable() {
return enable;
}

public void setEnable(String enable) {
this.enable = enable == null ? null : enable.trim();
}

public Integer getCreateBy() {
return createBy;
}

public void setCreateBy(Integer createBy) {
this.createBy = createBy;
}

public Date getCreateTime() {
return createTime;
}

public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
}

八、UserMapper.java

[code]package com.urthink.upfs.springbootmybatis.dao;

import com.urthink.upfs.springbootmybatis.entity.User;

import java.util.List;
import java.util.Map;

//@Mapper
public interface UserMapper {
int deleteByPrimaryKey(Integer id);

int insert(User record);

int insertSelective(User record);

User selectByPrimaryKey(Integer id);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);

List<User> getPageList(Map map);
}

九、UserMapper.xml

分页查询的sql需要自己写一下,getPageList

[code]<?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.urthink.upfs.springbootmybatis.dao.UserMapper">
<resultMap id="BaseResultMap" type="com.urthink.upfs.springbootmybatis.entity.User">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="password" jdbcType="VARCHAR" property="password" />
<result column="mobile" jdbcType="VARCHAR" property="mobile" />
<result column="enable" jdbcType="CHAR" property="enable" />
<result column="create_by" jdbcType="INTEGER" property="createBy" />
<result column="create_time" jdbcType="TIMESTAMP" property="createTime" />
</resultMap>
<sql id="Base_Column_List">
id, user_name, password, mobile, enable, create_by, create_time
</sql>

<!-- 分页查询 -->
<select id="getPageList" resultType="com.urthink.upfs.springbootmybatis.entity.User" parameterType="map">
select t.*
from t_user t
<where>
<if test="userName != null and userName != ''">
and r.user_name like concat(concat('%',#{userName}),'%')
</if>
</where>
<!-- order by CONVERT(t.user_name USING gbk) asc -->
</select>

<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from t_user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.urthink.upfs.springbootmybatis.entity.User">
insert into t_user (id, user_name, password,
mobile, enable, create_by,
create_time)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},
#{mobile,jdbcType=VARCHAR}, #{enable,jdbcType=CHAR}, #{createBy,jdbcType=INTEGER},
#{createTime,jdbcType=TIMESTAMP})
</insert>
<insert id="insertSelective" parameterType="com.urthink.upfs.springbootmybatis.entity.User">
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="userName != null">
user_name,
</if>
<if test="password != null">
password,
</if>
<if test="mobile != null">
mobile,
</if>
<if test="enable != null">
enable,
</if>
<if test="createBy != null">
create_by,
</if>
<if test="createTime != null">
create_time,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="id != null">
#{id,jdbcType=INTEGER},
</if>
<if test="userName != null">
#{userName,jdbcType=VARCHAR},
</if>
<if test="password != null">
#{password,jdbcType=VARCHAR},
</if>
<if test="mobile != null">
#{mobile,jdbcType=VARCHAR},
</if>
<if test="enable != null">
#{enable,jdbcType=CHAR},
</if>
<if test="createBy != null">
#{createBy,jdbcType=INTEGER},
</if>
<if test="createTime != null">
#{createTime,jdbcType=TIMESTAMP},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.urthink.upfs.springbootmybatis.entity.User">
update t_user
<set>
<if test="userName != null">
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="password != null">
password = #{password,jdbcType=VARCHAR},
</if>
<if test="mobile != null">
mobile = #{mobile,jdbcType=VARCHAR},
</if>
<if test="enable != null">
enable = #{enable,jdbcType=CHAR},
</if>
<if test="createBy != null">
create_by = #{createBy,jdbcType=INTEGER},
</if>
<if test="createTime != null">
create_time = #{createTime,jdbcType=TIMESTAMP},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.urthink.upfs.springbootmybatis.entity.User">
update t_user
set user_name = #{userName,jdbcType=VARCHAR},
password = #{password,jdbcType=VARCHAR},
mobile = #{mobile,jdbcType=VARCHAR},
enable = #{enable,jdbcType=CHAR},
create_by = #{createBy,jdbcType=INTEGER},
create_time = #{createTime,jdbcType=TIMESTAMP}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>

十、UserService.java

[code]package com.urthink.upfs.springbootmybatis.servcie;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.urthink.upfs.springbootmybatis.dao.UserMapper;
import com.urthink.upfs.springbootmybatis.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Transactional(readOnly = true)
@Service
public class UserService {

@Autowired
private UserMapper userMapper;

@Transactional(readOnly = false)
public int deleteByPrimaryKey(Integer id){
return userMapper.deleteByPrimaryKey(id);
}

@Transactional(readOnly = false)
public int insert(User user){
return userMapper.insert(user);
}

@Transactional(readOnly = false)
public int insertSelective(User user){
return userMapper.insertSelective(user);
}

public User selectByPrimaryKey(Integer id){
return userMapper.selectByPrimaryKey(id);
}

@Transactional(readOnly = false)
public int updateByPrimaryKeySelective(User user){
return userMapper.updateByPrimaryKeySelective(user);
}

@Transactional(readOnly = false)
public int updateByPrimaryKey(User user){
return userMapper.updateByPrimaryKey(user);
}

/**
* 分页查询
* @param map
* @return
*/
public PageInfo<User> getPageInfo(Map map) {
if(map.get("pageNum")!=null && map.get("pageSize")!=null) {
PageHelper.startPage((Integer) map.get("pageNum"), (Integer) map.get("pageSize"));
}
if (map.get("orderBy") != null) {
PageHelper.orderBy(map.get("orderBy").toString());
}
List<User> list = userMapper.getPageList(map);
PageInfo pageInfo = new PageInfo(list);
return pageInfo;
}

}

十一、测试类

[code]package com.urthink.upfs.springbootmybatis;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.urthink.upfs.springbootmybatis.dao.UserMapper;
import com.urthink.upfs.springbootmybatis.entity.User;
import com.urthink.upfs.springbootmybatis.servcie.UserService;
import org.apache.ibatis.session.RowBounds;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
* mybatis测试类
* https://github.com/pagehelper/Mybatis-PageHelper/blob/master/wikis/zh/HowToUse.md
* @author zhao
* @date 2019.1.21
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional //支持事物,@SpringBootTest 事物默认自动回滚
@Rollback // 事务自动回滚,不自动回滚@Rollback(false)
public class MybatisTest {

@Autowired
private SqlSessionTemplate sqlSessionTemplate;
@Autowired
private UserService userService;
@Autowired
private UserMapper userMapper;

@Test
public void sqlSessionTemplateTest() {
User user = sqlSessionTemplate.selectOne("com.urthink.upfs.springbootmybatis.dao.UserMapper.selectByPrimaryKey",1000);
System.out.println(user.getUserName());
}

@Test
public void selectTest() {
User user = userService.selectByPrimaryKey(1000);
System.out.println(user.getUserName());
}

@Test
public void insertTest() {
User user = new User();
user.setUserName("test");
user.setPassword("test"); //需加密
user.setEnable("1");
user.setCreateBy(1);
user.setCreateTime(new Date());
int r = userService.insert(user);
System.out.println(r);
}

@Test
public void pageTest1() {
//第一种,RowBounds方式的调用,需要把rowBoundsWithCount设置为true
List<User> userList = sqlSessionTemplate.selectList("com.urthink.upfs.springbootmybatis.dao.UserMapper.getPageList", null, new RowBounds(0, 10));
//用PageInfo对结果进行包装
PageInfo pageInfo = new PageInfo(userList);
//PageInfo包含了非常全面的分页属性
System.out.println("当前页:" + pageInfo.getPageNum());
System.out.println("每页的数量:" + pageInfo.getPageSize());
System.out.println("总记录数:" + pageInfo.getTotal());
System.out.println("结果集:" + pageInfo.getList());
}

@Test
public void pageTest2() {
//第二种,Mapper接口方式的调用,推荐这种使用方式。
PageHelper.startPage(1, 10);
//排序
PageHelper.orderBy("create_time asc, id asc");
List<User> list = userMapper.getPageList(null);
//用PageInfo对结果进行包装
PageInfo pageInfo = new PageInfo(list);

//测试PageInfo全部属性
//PageInfo包含了非常全面的分页属性
System.out.println("当前页:" + pageInfo.getPageNum());
System.out.println("每页的数量:" + pageInfo.getPageSize());
System.out.println("当前页的数量:" + pageInfo.getSize());
System.out.println("当前页面第一个元素在数据库中的行号:" + pageInfo.getStartRow());
System.out.println("当前页面最后一个元素在数据库中的行号:" + pageInfo.getEndRow());
System.out.println("总页数:" + pageInfo.getPages());
System.out.println("前一页:" + pageInfo.getPrePage());
System.out.println("下一页:" + pageInfo.getNextPage());
System.out.println("是否为第一页:" + pageInfo.isIsFirstPage());
System.out.println("是否为最后一页:" + pageInfo.isIsLastPage());
System.out.println("是否有前一页:" + pageInfo.isHasPreviousPage());
System.out.println("是否有下一页:" + pageInfo.isHasNextPage());
System.out.println("导航页码数:" + pageInfo.getNavigatePages());
System.out.println("所有导航页号:" + pageInfo.getNavigatepageNums());
System.out.println("导航条上的第一页:" + pageInfo.getNavigateFirstPage());
System.out.println("导航条上的最后一页:" + pageInfo.getNavigateLastPage());

System.out.println("总记录数:" + pageInfo.getTotal());
System.out.println("结果集:" + pageInfo.getList());

System.out.println(list.size());

}
}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: