springboot 2.0 集成mybatis,mybatis-generator,pagehelper

springboot 2.0 集成mybatis,通用Mapper tk.mybatis, mybatis-generator,pagehelper

https://blog.csdn.net/haveqing/article/details/86621768

开发工具idea

springboot 2.0.8

一、pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.8.RELEASE
         
    
    com.urthink.upfs
    springboot-mybatis
    0.0.1-SNAPSHOT
    springboot-mybatis
    springboot-mybatis project for Spring Boot

    
        1.8
    

    
        
        
            org.springframework.boot
            spring-boot-starter
            
                
                    org.springframework.boot
                    spring-boot-starter-logging
                
            
        

        
        
            org.springframework.boot
            spring-boot-starter-log4j2
        

        
            org.springframework.boot
            spring-boot-starter-web
        

        
            com.alibaba
            druid-spring-boot-starter
            1.1.10
        

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.2
        

        
            mysql
            mysql-connector-java
            runtime
        

        
            org.mybatis.generator
            mybatis-generator-core
            1.3.7
        

        
            com.github.pagehelper
            pagehelper-spring-boot-starter
            1.2.9
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.7
                
                    
                    src/main/resources/generatorConfig.xml
                    true
                    true
                
            
        

        
            
                src/main/resources
                
                
                    **/*.properties
                    **/*.xml
                    **/*.yml
                
                false
            
            
                src/main/java
                
                    **/*.xml
                
                false
            
        
    


二、application.yml

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







    
    
        
        
            
            
        
        
        
            
        
        
        
            
                
                
                
            
            
            
                
                
            
            
            
        

        
            
                
                
            
            
            
                
                
            
            
            
        

        
            
            
            
                
                
            
            
            
        

    
    
    
        
        
        
        
        

        
            
            
            
            
        
    


四、SpringbootMybatisApplication.java

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




	
    
  	
        
        
        
        
        
        
            
			
            
        
		
        
        
        
            
        

        
 		
        
            
            
            
            
            
            
            
            
        
        
        
            
        

        
      	
        
            
        
        
		

        

idea,双击运行

springboot 2.0 集成mybatis,mybatis-generator,pagehelper_第1张图片

六、建表脚本sql

/*
 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;

七、实体类

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

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 getPageList(Map map);
}

九、UserMapper.xml

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




  
    
    
    
    
    
    
    
  
  
    id, user_name, password, mobile, enable, create_by, create_time
  

  
  

  
  
    delete from t_user
    where id = #{id,jdbcType=INTEGER}
  
  
    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 into t_user
    
      
        id,
      
      
        user_name,
      
      
        password,
      
      
        mobile,
      
      
        enable,
      
      
        create_by,
      
      
        create_time,
      
    
    
      
        #{id,jdbcType=INTEGER},
      
      
        #{userName,jdbcType=VARCHAR},
      
      
        #{password,jdbcType=VARCHAR},
      
      
        #{mobile,jdbcType=VARCHAR},
      
      
        #{enable,jdbcType=CHAR},
      
      
        #{createBy,jdbcType=INTEGER},
      
      
        #{createTime,jdbcType=TIMESTAMP},
      
    
  
  
    update t_user
    
      
        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 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}
  

十、UserService.java

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 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 list = userMapper.getPageList(map);
        PageInfo pageInfo = new PageInfo(list);
        return pageInfo;
    }

}

十一、测试类

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 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 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());

	}
}

idea mybatis相关插件推荐

插件
1.jrebel

动态加载类
2.free mybatis plugin

方便在mapper.java和mapper.xml 之间切换
3.mybatis log plugin 查看sql语句,把参数填充好

把 mybatis 输出的sql日志还原成完整的sql语句。 
将日志输出的sql语句中的问号 ? 替换成真正的参数值。 
通过 "Tools -> MyBatis Log Plugin" 菜单或快捷键 "Ctrl+Shift+Alt+O" 启用。 
点击窗口左边的 "Filter" 按钮,可以过滤不想要输出的sql语句。 
点击窗口左边的 "Format Sql" 按钮,可以格式化输出的sql语句。 
选中console的sql日志,右击 "Restore Sql from Selection" 菜单可以还原sql语句。 
前提条件:输出的sql日志必须包含"Preparing:"和"Parameters:"才能正常解析。

你可能感兴趣的:(mybatis,springboot)