Spring Boot 集成教程
- Spring Boot 介绍
- Spring Boot 开发环境搭建(Eclipse)
- Spring Boot Hello World (restful接口)例子
- spring boot 连接Mysql
- spring boot配置druid连接池连接mysql
- spring boot集成mybatis(1)
- spring boot集成mybatis(2) – 使用pagehelper实现分页
- spring boot集成mybatis(3) – mybatis generator 配置
- spring boot 接口返回值封装
- spring boot输入数据校验(validation)
- spring boot rest 接口集成 spring security(1) – 最简配置
- spring boot rest 接口集成 spring security(2) – JWT配置
- spring boot 异常(exception)处理
- spring boot 环境配置(profile)切换
- spring boot redis 缓存(cache)集成
概述
MyBatis是一个开源的持久层框架,现在互联网项目使用比较多,MyBatis简化了Java应用程序中对数据库的访问,实现了诸如动态SQL、结果集映射等,高效又不失灵活,简单地说,它是JDBC和Hibernate的替代品,个人在项目中倾向使用mybatis。本文介绍在spring boot项目中集成mybatis过程。
准备数据
我们会使用与前面章节 [spring boot 连接 mysql] 同样的数据,如无数据请参照该文准备数据,该文详细介绍了通过mysql图形客户端workbench生成数据的过程。如果倾向使用mysql命令行客户端,下面是创建数据库和插入数据的sql语句。
sql语句
mysql命令行客户端连接数据库:
mysql -h localhost -u root -p
创建数据库
CREATE DATABASE qikegu_demo CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
创建表的sql语句:
CREATE TABLE `qikegu_demo`.`user` (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`nickname` VARCHAR(50) NULL COMMENT '昵称',
`mobile` VARCHAR(20) NULL COMMENT '手机号',
`password` CHAR(60) NULL COMMENT '密码hash值',
`role` VARCHAR(100) NULL DEFAULT 'user' COMMENT '角色,角色名以逗号分隔',
PRIMARY KEY (`id`),
UNIQUE INDEX `mobile_UNIQUE` (`mobile` ASC))
COMMENT = '用户表';
插入数据的sql语句:
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc1', '13512345678', '123');
INSERT INTO `qikegu_demo`.`user` (`nickname`, `mobile`, `password`) VALUES ('abc2', '13512345677', '123');
创建项目
创建spring boot项目
打开Eclipse,创建spring boot的spring starter project项目,在配置依赖时,勾选web, jdbc, mysql,mybatis,如不清楚怎样创建spring boot项目,参照章节: [spring boot hello world (restful接口)例子]
pom.xml文件
自动生成的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 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.qikegu</groupId>
<artifactId>springboot-mybatis-demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mybatis-demo</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.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</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>
</plugins>
</build>
</project>
经典项目结构
添加一些目录,创建经典的项目结构(mvc),如下图:
src/main/java/com/qikegu/demo 文件夹下添加目录:
- common - 公用代码
- config - spring java配置文件
- controller - 控制层
- model - 对象层
- repository - 数据库访问层,保存mybatis的映射类
- service - 服务层
src/main/resources文件夹下添加目录:
- mapper - mybatis sql映射xml文件
配置
application.properties配置
## 服务器端口,如果不配置默认是8080端口
server.port=8096
## 数据库设置
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/qikegu_demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=你的密码
## mybatis配置
# 参数类型的包别名设置
mybatis.typeAliasesPackage=com.qikegu.demo.model
# 指向映射xml文件目录
mybatis.mapperLocations=classpath:mapper/*.xml
数据库配置不作说明了,不清楚可以参照 [spring boot 连接 mysql]。
mybatis配置说明一下,typeAliasesPackage:参数类型的包别名设置,设置这个以后xml映射文件在parameterType的值就不用写成全路径名了,parameterType="com.qikegu.demo.model.User"可以写成parameterType = "User"。
@MapperScan注解
@MapperScan的作用是指定要扫描的mybatis映射类的路径,放在应用类的前面:
package com.qikegu.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
//指定要扫描的mybatis映射类的路径
@MapperScan("com.qikegu.demo.repository")
public class SpringbootMybatisDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisDemoApplication.class, args);
}
}
添加代码
我们实现一个通过用户id查询用户信息的接口。
添加的文件如下图:
调用过程:用户访问 > UserController > UserService > UserMapper.java > UserMapper.xml > 数据库
,返回User对象
下面列出每个文件内容,重要地方都已注释
User.java - 对象类
package com.qikegu.demo.model;
public class User {
private long id;
private String nickname;
private String mobile;
@JsonProperty(access = Access.WRITE_ONLY) //在输出的Json数据中隐藏密码,只能输入不输出
private String password;
private String role;
public User(long id, String nickname, String mobile, String password, String role) {
this.id = id;
this.nickname = nickname;
this.mobile = mobile;
this.password = password;
this.role = role;
}
public User() {
super();
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
UserService.java - 服务接口类
package com.qikegu.demo.service;
import com.qikegu.demo.model.User;
public interface UserService {
public User getUserById(long userId);
}
UserServiceImpl - 服务接口实现类
package com.qikegu.demo.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import com.qikegu.demo.model.User;
import com.qikegu.demo.repository.UserMapper;
import com.qikegu.demo.service.UserService;
@Service("userService")
public class UserServiceImpl implements UserService {
// 注入mapper类
@Resource
private UserMapper userMapper;
@Override
public User getUserById(long userId) {
return userMapper.selectByPrimaryKey(userId);
}
}
UserController - 控制类
package com.qikegu.demo.controller;
import javax.annotation.Resource;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.qikegu.demo.model.User;
import com.qikegu.demo.service.UserService;
@RestController
@EnableAutoConfiguration
@RequestMapping("/user")
public class UserController {
// 注入mapper类
@Resource
private UserService userService;
@RequestMapping(value="{id}", method=RequestMethod.GET, produces="application/json")
public User getUser(@PathVariable long id) throws Exception {
User user = this.userService.getUserById(id);
return user;
}
}
UserMapper.java - mybatis映射类,数据库访问层
package com.qikegu.demo.repository;
import com.qikegu.demo.model.User;
public interface UserMapper {
// 对应xml映射文件元素的ID
User selectByPrimaryKey(long id);
}
UserMapper.xml - mybatis 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.qikegu.demo.repository.UserMapper">
<resultMap id="BaseResultMap" type="com.qikegu.demo.model.User">
<constructor>
<idArg column="id" javaType="_long" jdbcType="BIGINT" />
<arg column="nickname" javaType="java.lang.String" jdbcType="VARCHAR" />
<arg column="mobile" javaType="java.lang.String" jdbcType="VARCHAR" />
<arg column="password" javaType="java.lang.String" jdbcType="CHAR" />
<arg column="role" javaType="java.lang.String" jdbcType="VARCHAR" />
</constructor>
</resultMap>
<sql id="Base_Column_List">
id, nickname, mobile, password, role
</sql>
<select id="selectByPrimaryKey" parameterType="_long" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=BIGINT}
</select>
</mapper>
运行
项目的右键菜单,选择:run as -> spring boot app 运行程序,浏览器访问获取用户信息:
总结
本文件介绍了spring boot集成mybatis的过程,集成过程总结如下:
- 创建项目设置依赖时勾选mybatis依赖
- application.properties设置
- @MapperScan注解设置
- 写映射xml文件与映射java类
- 在controller或service中调用映射类的方法
经过测试,集成成功。