Spring boot 2.1.1 整合 mybatis (超详细)
在idea 14以上版本中就已经支持创建Spring Boot
本项目使用的环境:
开发工具:
- intellij idea 2018.2
- jdk1.8
- maven3.3.9
额外功能:
- PageHelper 分页插件
- mybatis generator 自动生成代码插件
image.png1.点击菜单栏 File -> New ->Project 创建项目
image.png
image.png image.png
image.png
image.png
-
看一下项目的初始结构:
image.png
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 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.1.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mhg</groupId>
<artifactId>mhg</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>mhg</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.0</version>
</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.35</version>
</dependency>
<!--alibaba的druid数据库连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-joda</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.module</groupId>
<artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<!-- 分页插件 :该版本只支持spring boot2.0以上版本-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- mybatis generator 自动生成代码插件 -->
<plugin>
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<configurationFile>${basedir}/src/main/resources/generator/generatorConfig.xml</configurationFile>
<overwrite>true</overwrite>
<verbose>true</verbose>
</configuration>
</plugin>
</plugins>
</build>
</project>
- 项目不使用application.properties文件 而使用更加简洁的application.yml文件:
将原有的resource文件夹下的application.properties文件删除,创建一个新的application.yml配置文件,
文件的内容如下:
server:
port: 8080
spring:
datasource:
name: test
url: jdbc:mysql://112.74.133.224: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文件
image.png - 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>
<!-- 数据库驱动:选择你的本地硬盘上面的数据库驱动包-->
<classPathEntry location="D:\myFile\software\apache-maven-3.1.1\localhost_repository\mysql\mysql-connector-java\5.1.6\mysql-connector-java-5.1.6.jar"/>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressDate" value="true"/>
<!-- 是否去除自动生成的注释 true:是 : false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!--数据库链接URL,用户名、密码 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://112.74.133.224:3306/mytest?characterEncoding=utf-8" userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- 生成模型的包名和位置-->
<javaModelGenerator targetPackage="main.java.com.mhg.model" targetProject="src">
<property name="enableSubPackages" value="true"/>
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- 生成映射文件的包名和位置-->
<sqlMapGenerator targetPackage="main.resources.mapping" targetProject="src">
<property name="enableSubPackages" value="true"/>
</sqlMapGenerator>
<!-- 生成DAO的包名和位置-->
<javaClientGenerator type="XMLMAPPER" targetPackage="main.java.com.mhg.mapper" targetProject="src">
<property name="enableSubPackages" value="true"/>
</javaClientGenerator>
<!-- 要生成的表 tableName是数据库中的表名或视图名 domainObjectName是实体类名-->
<table tableName="t_user" domainObjectName="User" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false"></table>
</context>
</generatorConfiguration>
-
下面将演示如何在intellij idea下运行generator自动生成代码:
点击run-Edit Configurations
image.png
参数:mybatis-generator:generate -e
image.png
-
运行
image.png -
最后生成的文件以及结构:
image.png
注意:由于生成的类中的路径写了全路径,需要把前面多余的"main.java."删除,
image.png
- 生成的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<User> 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
<?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.mhg.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.mhg.model.User" >
<id column="user_id" property="userId" jdbcType="INTEGER" />
<result column="user_name" property="userName" jdbcType="VARCHAR" />
</resultMap>
<sql id="Base_Column_List" >
user_id, user_name
</sql>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from t_user
where user_id = #{userId,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from t_user
where user_id = #{userId,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.mhg.model.User" >
insert into t_user (user_id, user_name)
values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.mhg.model.User" >
insert into t_user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="userId != null" >
user_id,
</if>
<if test="userName != null" >
user_name,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="userId != null" >
#{userId,jdbcType=INTEGER},
</if>
<if test="userName != null" >
#{userName,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.mhg.model.User" >
update t_user
<set >
<if test="userName != null" >
user_name = #{userName,jdbcType=VARCHAR},
</if>
</set>
where user_id = #{userId,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.mhg.model.User" >
update t_user
set user_name = #{userName,jdbcType=VARCHAR}
where user_id = #{userId,jdbcType=INTEGER}
</update>
<select id="selectAllUser" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from t_user
</select>
</mapper>
-
.打开springboot的启动类。需要增加@MapperScan注解,(为了让spring boot扫描mapper文件)
image.png
- 编写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<User> 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<User> 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:
image.png
测试分页:
image.png
网友评论