Spring boot 2.1.1 整合 mybatis (超详细)
在idea 14以上版本中就已经支持创建Spring Boot
本项目使用的环境:
开发工具:
- intellij idea 2018.2
- jdk1.8
- maven3.3.9
额外功能:
- PageHelper 分页插件
- mybatis generator 自动生成代码插件
1.点击菜单栏 File -> New ->Project 创建项目
- 看一下项目的初始结构:
pom文件:
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.1.1.RELEASE
com.mhg
mhg
0.0.1-SNAPSHOT
jar
mhg
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter-jdbc
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.0
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
mysql
mysql-connector-java
5.1.35
com.alibaba
druid-spring-boot-starter
1.1.9
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
org.springframework.boot
spring-boot-maven-plugin
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
${basedir}/src/main/resources/generator/generatorConfig.xml
true
true
- 项目不使用application.properties文件 而使用更加简洁的application.yml文件:
将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件,
文件的内容如下:
server:
port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://127.0.0.1:3306/mytest
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
mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.yxzjfk.model
#pagehelper分页插件
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
- 下一步就是创建数据库:
CREATE DATABASE mytest;
CREATE TABLE t_user(
user_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
user_name VARCHAR(255) NOT NULL ,
) ENGINE=INNODB AUTO_INCREMENT=1000 DEFAULT CHARSET=utf8;
- 使用mybatis generator 自动生成代码,在resource下新建一个generator目录、随后建立generatorConfig.xml文件
- generatorConfig.xml内容如下:
- 下面将演示如何在intellij idea下运行generator自动生成代码:
点击run-Edit Configurations
参数:mybatis-generator:generate -e
别忘记在 pom文件下 增加依赖!!
- 运行
- 最后生成的文件以及结构:
注意:由于生成的类中的路径写了全路径,需要把前面多余的"main.java."删除,
- 生成的UserMapper.java
package com.yxzjfk.mapper;
import com.yxzjfk.model.User;
import java.util.List;
public interface UserMapper {
int deleteByPrimaryKey(Integer userId);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer userId);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List selectAllUser();
}
- 生成的User.java
package com.mhg.model;
public class User {
private Integer userId;
private String userName;
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
}
- 生成的UserMapper.xml
user_id, user_name
delete from t_user
where user_id = #{userId,jdbcType=INTEGER}
insert into t_user (user_id, user_name)
values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR})
insert into t_user
user_id,
user_name,
#{userId,jdbcType=INTEGER},
#{userName,jdbcType=VARCHAR},
update t_user
user_name = #{userName,jdbcType=VARCHAR},
where user_id = #{userId,jdbcType=INTEGER}
update t_user
set user_name = #{userName,jdbcType=VARCHAR}
where user_id = #{userId,jdbcType=INTEGER}
- .打开springboot的启动类。需要增加@MapperScan注解,(为了让spring boot扫描mapper文件)
- 编写service 、serviceImpl、controller类 来进行测试:
UserService :
package com.mhg.service;
import com.mhg.model.User;
import java.util.List;
public interface UserService {
/**
* 添加User
* @param user
* @return
*/
int addUser(User user);
/**
* 查询User集合
* @param pageNum
* @param pageSize
* @return
*/
List findUserAll(int pageNum, int pageSize);
}
UserServiceImpl:
package com.mhg.service.impl;
import com.github.pagehelper.PageHelper;
import com.mhg.mapper.UserMapper;
import com.mhg.model.User;
import com.mhg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;//由于intellij idea检测级别,导致这里会报错,但是不影响运行
@Override
public int addUser(User user) {
return userMapper.insertSelective(user);
}
/*
* 这个方法中用到了配置依赖的分页插件pagehelper
* 很简单,只需要在service层传入参数,然后将参数传递给一个插件的一个静态方法即可;
* pageNum 开始页数
* pageSize 每页显示的数据条数
* */
@Override
public List findUserAll(int pageNum, int pageSize) {
//将参数传给这个方法就可以实现物理分页
PageHelper.startPage(pageNum, pageSize);
return userMapper.selectAllUser();
}
}
UserController:
package com.mhg.controller;
import com.mhg.model.User;
import com.mhg.service.UserService;
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;
@Controller
@RequestMapping(value = "/user")
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@RequestMapping(value = "/addUser")
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){
System.out.print(pageNum);
return userService.findUserAll(pageNum,pageSize);
}
@ResponseBody
@RequestMapping(value = "/hello")
public String hello(){
return "周杰伦";
}
}
让我们测试一下添加User:
测试分页: