spring-boot整合mybatis
新建项目
访问spring官网 https://start.spring.io/ 根据需求进行创建项目
具体如下所示,以来选择spring web,JDBC Api, Mybatis framwork, mysql Driver:
创建完成后,浏览器会下载一个压缩包,解压到自定义目录,并用idea打开并按照下面目录建起项目结构
项目结构
pom.xml配置
<?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 https://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.5.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.mybatis</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</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>
<!--Mybatis-generator插件,用于自动生成Mapper和POJO-->
<groupId>org.mybatis.generator</groupId>
<artifactId>mybatis-generator-maven-plugin</artifactId>
<version>1.3.2</version>
<configuration>
<!--配置文件的位置-->
<configurationFile>src/main/resources/mybatis-generator.xml</configurationFile>
<verbose>true</verbose>
<overwrite>true</overwrite>
</configuration>
</plugin>
</plugins>
</build>
</project>
数据库表生成
##用户表
DROP TABLE IF EXISTS `prod_user`;
create table `prod_user` (
id int(11) not null AUTO_INCREMENT,
user_name varchar(50) not null COMMENT '用户名',
user_pass varchar(255) not null COMMENT '密码',
role varchar(50) default null ,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
#插入数据
insert into `prod_user` values(1, 'admin1', '123456','admin');
application.yml 配置文件
这里用application.yml代替application.properties。在resource目录下新建application.yml并配置一下数据
server:
port: 8080
spring:
datasource:
username: root
password: mysql
#url中database为对应的数据库名称
url: jdbc:mysql://localhost:3306/proddb?useUnicode=true&characterEncoding=utf-8&useSSL=true&serverTimezone=Asia/Shanghai
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.mybatis.demo.entity
#showSql
logging:
level:
com.example.demo.mapper: debug
这里driver-class-name为com.mysql.cj.jdbc.Driver,这是mysql-connect 6的用法,与之前相比需要在url中加入时区“serverTimezone=Asia/Shanghai”
mapper.xml文件的生成
如果想用mybatis-generate自动生成工具的请参考
链接: mybatis-generate如何使用.
注意:这里生成的mapper.xml文件,会出现两份完全一样的代码,我目前还没搞清楚,如果使用自动生成的,请删除mapper.xml中的重复代码。
<!--ProdUserMapper.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.mybatis.demo.mapper.ProdUserMapper">
<resultMap id="BaseResultMap" type="com.mybatis.demo.entity.ProdUser">
<id column="id" jdbcType="INTEGER" property="id" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="user_pass" jdbcType="VARCHAR" property="userPass" />
<result column="role" jdbcType="VARCHAR" property="role" />
</resultMap>
<sql id="Base_Column_List">
id, user_name, user_pass, role
</sql>
<select id="selectByPrimaryKey" parameterType="java.lang.Integer" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from prod_user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer">
delete from prod_user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.mybatis.demo.entity.ProdUser">
insert into prod_user (id, user_name, user_pass,
role)
values (#{id,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{userPass,jdbcType=VARCHAR},
#{role,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.mybatis.demo.entity.ProdUser">
insert into prod_user
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="id != null">
id,
</if>
<if test="userName != null">
user_name,
</if>
<if test="userPass != null">
user_pass,
</if>
<if test="role != null">
role,
</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="userPass != null">
#{userPass,jdbcType=VARCHAR},
</if>
<if test="role != null">
#{role,jdbcType=VARCHAR},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.mybatis.demo.entity.ProdUser">
update prod_user
<set>
<if test="userName != null">
user_name = #{userName,jdbcType=VARCHAR},
</if>
<if test="userPass != null">
user_pass = #{userPass,jdbcType=VARCHAR},
</if>
<if test="role != null">
role = #{role,jdbcType=VARCHAR},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.mybatis.demo.entity.ProdUser">
update prod_user
set user_name = #{userName,jdbcType=VARCHAR},
user_pass = #{userPass,jdbcType=VARCHAR},
role = #{role,jdbcType=VARCHAR}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
mapper接口文件的生成
package com.mybatis.demo.mapper;
import com.mybatis.demo.entity.ProdUser;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
@Mapper //告诉spring容器,让其扫描到
public interface ProdUserMapper {
int deleteByPrimaryKey(Integer id);
int insert(ProdUser record);
int insertSelective(ProdUser record);
ProdUser selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(ProdUser record);
int updateByPrimaryKey(ProdUser record);
}
实体类生成
package com.mybatis.demo.entity;
public class ProdUser {
private Integer id;
private String userName;
private String userPass;
private String role;
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 getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass == null ? null : userPass.trim();
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role == null ? null : role.trim();
}
@Override
public String toString() {
return "ProdUser{" +
"id=" + id +
", userName='" + userName + '\'' +
", userPass='" + userPass + '\'' +
", role='" + role + '\'' +
'}';
}
}
Service层
@Service
public class ProdUserService {
@Autowired
private ProdUserMapper prodUserMapper;
public ProdUser getUserInfo(int id) {
return prodUserMapper.selectByPrimaryKey(id);
}
}
Controller层
@RestController
@RequestMapping("/mybatis")
public class ProdUserController {
@Autowired
ProdUserService prodUserService;
@GetMapping("/getUser")
public String getProdUser(int id){
return prodUserService.getUserInfo(id).toString();
}
}
启动项目
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
验证
浏览器输入
http://localhost:8080/mybatis/getUser?id=2
得到如下界面: