Spring Boot2.0整合Mybatis(自动生成注解方式,多环境配置)

本介绍Spring Boot2.0整合Mybatis,通过MyBatis Generator插件自动生成mapper的sql注解及Provider类的过程,支持多环境的yml配置文件

首先用IDE开发工具(IDEA,STS,Eclipse)创建一个Spring Boot工程springboot-mybatis-demo-annotation, pom.xml如下



	4.0.0

	com.fhbean.springboot
	springboot-mybatis-demo-annotation
	0.0.1-SNAPSHOT
	jar

	springboot-mybatis-demo-annotation
	Demo project for Spring Boot

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.0.RELEASE
		 
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-jdbc
		
        
            org.springframework.boot  
            spring-boot-starter-actuator  
          
		
			org.springframework.boot
			spring-boot-starter-thymeleaf
		
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.mybatis.spring.boot
			mybatis-spring-boot-starter
			1.3.2
		
	    
	    
	       org.springframework.boot
	       spring-boot-starter-data-jpa
	    
		
			org.springframework.boot
			spring-boot-starter-test
			test
		
          
            org.springframework  
            spring-jdbc  
        
    
		
			mysql
			mysql-connector-java
			runtime
		
		
        
        
            com.alibaba
            druid
            1.0.11
        
        
            com.fasterxml.jackson.core
            jackson-core
        
        
            com.fasterxml.jackson.core
            jackson-databind
        
        
            com.fasterxml.jackson.datatype
            jackson-datatype-joda
        
        
            com.fasterxml.jackson.module
            jackson-module-parameter-names
        
        
        
            com.github.pagehelper
            pagehelper-spring-boot-starter
            1.2.3
        
        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.0
        
        
	

	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
			
			
            
                org.mybatis.generator
                mybatis-generator-maven-plugin
                1.3.6
                
                    ${basedir}/src/main/resources/generator/generatorConfig.xml
                    true
                    true
                
            
		
	




创建数据库springboot,采用utf-8字符集,并创建表t_user

CREATE TABLE `t_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_name` varchar(255) NOT NULL,
  `password` varchar(255) NOT NULL,
  `phone` varchar(255) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
在项目的/src/main/resources/generator下,创建一个generatorConfig.xml,内容如下:



    
    
    
        
            
            
            
        
        
        
        
        
            
        
        
        
            
            
        
        
        
            
        
        
        
        
            
        
        
        

注意这里的配置:

type的值是XMLMAPPER,则生成xml映射文件;是ANNOTATEDMAPPER,则生成的dao采用注解来写sql。

配置application.yml文件和application-dev.yml (具体说明请看这里 支持多环境配置)

application.yml

debug: false

mybatis: 
  mapper-locations: classpath:mapping/*.xml
  type-aliases-package: com.fhbean.springboot.mybatisdemo.model

#pagehelper分页插件
pagehelper:
  helperDialect: mysql
  reasonable: true
  supportMethodsArguments: true
  params: count=countSql
  
spring:
  profiles: 
    active: dev
    

application-dev.yml

server: 
  port: 8080

spring:
  profiles: dev
  datasource:
    name: test
    url: jdbc:mysql://127.0.0.1:3306/springboot?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
    username: root
    password: root
    # 使用druid数据源
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.jdbc.Driver
    filters: stat
    maxActive: 20
    initialSize: 1
    maxWait: 60000
    minIdle: 1
    timeBetweenEvictionRunsMillis: 60000
    minEvictableIdleTimeMillis: 300000
    validationQuery: select 'x'
    testWhileIdle: true
    testOnBorrow: false
    testOnReturn: false
    poolPreparedStatements: true
    maxOpenPreparedStatements: 20
    
若是采用STS或Eclipse,则安装一个MyBatis Generator插件[Help] --> [Eclipse Marketplace]

右键generatorConfig.xml,在弹出菜单选择[Run As] --> [Run MyBatis Generator]

随后在com.fhbean.springboot.mybatisdemo.model包下,生成一个名为User的JavaBean

public class User {

private Integer userId;
private String userName;
private String password;
private String phone;
....
}

在com.fhbean.springboot.mybatisdemo.mapper包下,会生成一个接口UserMapper和一个类UserSqlProvider

UserMapper内容如下:

package com.fhbean.springboot.mybatisdemo.mapper;

import com.fhbean.springboot.mybatisdemo.model.User;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.InsertProvider;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import org.apache.ibatis.annotations.UpdateProvider;
import org.apache.ibatis.type.JdbcType;

public interface UserMapper {
    @Delete({
        "delete from t_user",
        "where user_id = #{userId,jdbcType=INTEGER}"
    })
    int deleteByPrimaryKey(Integer userId);

    @Insert({
        "insert into t_user (user_id, user_name, ",
        "password, phone)",
        "values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, ",
        "#{password,jdbcType=VARCHAR}, #{phone,jdbcType=VARCHAR})"
    })
    int insert(User record);

    @InsertProvider(type=UserSqlProvider.class, method="insertSelective")
    int insertSelective(User record);

    @Select({
        "select",
        "user_id, user_name, password, phone",
        "from t_user",
        "where user_id = #{userId,jdbcType=INTEGER}"
    })
    @Results({
        @Result(column="user_id", property="userId", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="user_name", property="userName", jdbcType=JdbcType.VARCHAR),
        @Result(column="password", property="password", jdbcType=JdbcType.VARCHAR),
        @Result(column="phone", property="phone", jdbcType=JdbcType.VARCHAR)
    })
    User selectByPrimaryKey(Integer userId);
    
    
    @Select({
        "select",
        "user_id, user_name, password, phone",
        "from t_user"
    })
    @Results({
        @Result(column="user_id", property="userId", jdbcType=JdbcType.INTEGER, id=true),
        @Result(column="user_name", property="userName", jdbcType=JdbcType.VARCHAR),
        @Result(column="password", property="password", jdbcType=JdbcType.VARCHAR),
        @Result(column="phone", property="phone", jdbcType=JdbcType.VARCHAR)
    })
    public List selectAllUser();

    @UpdateProvider(type=UserSqlProvider.class, method="updateByPrimaryKeySelective")
    int updateByPrimaryKeySelective(User record);

    @Update({
        "update t_user",
        "set user_name = #{userName,jdbcType=VARCHAR},",
          "password = #{password,jdbcType=VARCHAR},",
          "phone = #{phone,jdbcType=VARCHAR}",
        "where user_id = #{userId,jdbcType=INTEGER}"
    })
    int updateByPrimaryKey(User record);
}
其中selectAllUser()是我手工加上去的。

UserSqlProvider

package com.fhbean.springboot.mybatisdemo.mapper;

import com.fhbean.springboot.mybatisdemo.model.User;
import org.apache.ibatis.jdbc.SQL;

public class UserSqlProvider {

    public String insertSelective(User record) {
        SQL sql = new SQL();
        sql.INSERT_INTO("t_user");
        
        if (record.getUserId() != null) {
            sql.VALUES("user_id", "#{userId,jdbcType=INTEGER}");
        }
        
        if (record.getUserName() != null) {
            sql.VALUES("user_name", "#{userName,jdbcType=VARCHAR}");
        }
        
        if (record.getPassword() != null) {
            sql.VALUES("password", "#{password,jdbcType=VARCHAR}");
        }
        
        if (record.getPhone() != null) {
            sql.VALUES("phone", "#{phone,jdbcType=VARCHAR}");
        }
        
        return sql.toString();
    }

    public String updateByPrimaryKeySelective(User record) {
        SQL sql = new SQL();
        sql.UPDATE("t_user");
        
        if (record.getUserName() != null) {
            sql.SET("user_name = #{userName,jdbcType=VARCHAR}");
        }
        
        if (record.getPassword() != null) {
            sql.SET("password = #{password,jdbcType=VARCHAR}");
        }
        
        if (record.getPhone() != null) {
            sql.SET("phone = #{phone,jdbcType=VARCHAR}");
        }
        
        sql.WHERE("user_id = #{userId,jdbcType=INTEGER}");
        
        return sql.toString();
    }
}

UserMapper中,所有的动态SQL,都定义在类UserSqlProvider中。若要增加新的动态SQL,只需在UserSqlProvider中增加相应的方法,并在UserMapper中增加相应的引用即可,如:@UpdateProvider(type=UserSqlProvider.class, method="updateByPrimaryKeySelective")。

给SpringbootMybatisDemoAnnotationApplication增加注解@MapperScan

package com.fhbean.springboot.mybatisdemo;

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

@SpringBootApplication
@MapperScan("com.fhbean.springboot.mybatisdemo.mapper")
public class SpringbootMybatisDemoAnnotationApplication {

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

编写UserController

package com.fhbean.springboot.mybatisdemo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fhbean.springboot.mybatisdemo.model.User;
import com.fhbean.springboot.mybatisdemo.service.UserService;

@Controller
@RequestMapping(value = "/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@ResponseBody
	@RequestMapping(value = "/add", produces = {"application/json;charset=UTF-8"})
	public int addUser(User user) {
		return userService.addUser(user);
	}
	
	@ResponseBody
	@RequestMapping(value = "/all/{pageNum}/{pageSize}", produces = "application/json;charset=UTF-8")
	public Object findAllUser(@PathVariable("pageNum") int pageNum, 
			@PathVariable("pageSize") int pageSize) {
		return userService.findAllUser(pageNum, pageSize);
	}
	
}

编写接口UserService

package com.fhbean.springboot.mybatisdemo.service;

import java.util.List;

import com.fhbean.springboot.mybatisdemo.model.User;

public interface UserService {

	int addUser(User user);
	
	List findAllUser(int pageNum, int pageSize);
	
}
编写接口的实现类UserServiceImpl,UserMapper自动注入
package com.fhbean.springboot.mybatisdemo.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fhbean.springboot.mybatisdemo.mapper.UserMapper;
import com.fhbean.springboot.mybatisdemo.model.User;
import com.fhbean.springboot.mybatisdemo.service.UserService;
import com.github.pagehelper.PageHelper;

@Service(value = "userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserMapper userMapper;
	
	@Override
	public int addUser(User user) {
		
		return userMapper.insertSelective(user);
	}

    /*
    * 这个方法中用到了我们开头配置依赖的分页插件pagehelper
    * 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
    * pageNum 开始页数
    * pageSize 每页显示的数据条数
    * */
	@Override
	public List findAllUser(int pageNum, int pageSize) {
		//将参数传给这个方法就可以实现物理分页了,非常简单。
		PageHelper.startPage(pageNum, pageSize);
		return userMapper.selectAllUser();
	}

}

启动Spring Boot工程


在浏览器录入http://localhost:8080/user/add?userName=张三&password=123&phone=13012345678

录入几条记录,

http://localhost:8080/user/all/1/5

会看到先前录入成功的数据。

[{"userId":1,"userName":"zhangsan","password":"123","phone":"13012345678"},{"userId":1000,"userName":"张三","password":"123","phone":"13012345678"},{"userId":1001,"userName":"李四","password":"123","phone":"13012345678"},{"userId":1002,"userName":"王五","password":"123","phone":"13012345678"},{"userId":1003,"userName":"马六","password":"123","phone":"13012345678"}]

项目结构图:

Spring Boot2.0整合Mybatis(自动生成注解方式,多环境配置)_第1张图片


参考:

https://blog.csdn.net/winter_chen001/article/details/77249029

https://blog.csdn.net/Winter_chen001/article/details/78622141

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