【SpringBoot 2學習筆記】《八》SpringBoot2資料庫訪問之整合MyBatis
My Batis 的官方定義:MyBatis是支援定製化SQL、儲存過程以及高階對映的優秀的持久層框架。MyBatis可以對配置和原生Map使用簡單的XML或註解,將介面和Java的POJO對映成資料庫中的記錄。可以看出,MyBatis是基於一種SQL到POJO的模型,它需要我們提供SQL、對映關係(XML或者註解,目前以XML 為主)和POJO 。與此同時,它還能支援動態SQL,以適應需求的變化,當前MyBatis漸漸成為市場的主流持久框架。MyBatis的配置檔案包括兩個大的部分,一是基礎配置檔案,一個是對映檔案。在MyBatis中也可以使用註解來實現對映,只是由於功能和可讀性的限制,在實際的專案使用得比較少,所以不介紹使用註解配置SQL的方式。
6.2.1 工程檔案中新增依賴包:pom.xml
<!-- 匯入mybatis依賴包 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.1</version>
</dependency>
mybatis-spring-boot-starter依賴:
- 自動檢測現有的DataSource
- 建立並註冊SqlSessionFactory的例項,該例項使用SqlSessionFactoryBean將該DataSource作為輸入進行傳遞
- 建立並註冊從SqlSessionFactory中獲取的SqlSessionTemplate的例項。
- 自動掃描您的mappers,將它們連結到SqlSessionTemplate並將其註冊到Spring上下文,以便將它們注入到您的bean中。
即當我們引入mybatis-spring-boot-starter之後,只需要在application.properties
定義一個DataSource,它會自動建立使用該DataSource的SqlSessionFactoryBean以及SqlSessionTemplate。同時會自動掃描我們指定的mappers,註冊到Spring上下文中。
6.2.2 配置資料來源
application.properties配置MySQL資料來源。
server.servlet.context-path=/gavin
server.port=9001
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://rm-wz98XXXXuo.mysql.rds.aliyuncs.com:3306/usermng?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
spring.datasource.username=gavin
spring.datasource.password=gavinpw
注意:現在有些文章中可能存在記述錯誤的地方。
spring.datasource.driverClassName
如果設定為:com.mysql.jdbc.Driver
,會引起編譯錯誤,給出的提示中已經說明了修改方法,將ClassName變更為:com.mysql.cj.jdbc.Driver
。
Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
全域性配置檔案 application.properties中spring.datasource下只配置了資料庫地址、連線驅動、賬號、密碼,預設使用的是HikariDataSource資料來源(com.zaxxer.hikari.HikariDataSource
)。
6.2.3 使用mybatis-generator-gui自動生成程式碼
詳細使用參考【11.1 使用mybatis-generator-gui自動生成mybatis關聯程式碼】
也可以下載直接編譯好的可執行的檔案:
1. 生成使用者資訊程式碼
package com.gavinbj.confmng.persistence.entity;
import java.io.Serializable;
import java.util.Date;
/**
* UserInfo
* @author gavinbj
*/
public class UserInfo implements Serializable {
private String userId;
/**
* 使用者姓名
*/
private String userName;
/**
* 個人介紹
*/
private String introduce;
/**
* 行動電話
*/
private String mobilephone;
/**
* 郵箱
*/
private String email;
/**
* 生日
*/
private Date birthday;
/**
* 性別
*/
private String gender;
private static final long serialVersionUID = 1L;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getIntroduce() {
return introduce;
}
public void setIntroduce(String introduce) {
this.introduce = introduce;
}
public String getMobilephone() {
return mobilephone;
}
public void setMobilephone(String mobilephone) {
this.mobilephone = mobilephone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
@Override
public boolean equals(Object that) {
if (this == that) {
return true;
}
if (that == null) {
return false;
}
if (getClass() != that.getClass()) {
return false;
}
UserInfo other = (UserInfo) that;
return (this.getUserId() == null ? other.getUserId() == null : this.getUserId().equals(other.getUserId()))
&& (this.getUserName() == null ? other.getUserName() == null : this.getUserName().equals(other.getUserName()))
&& (this.getIntroduce() == null ? other.getIntroduce() == null : this.getIntroduce().equals(other.getIntroduce()))
&& (this.getMobilephone() == null ? other.getMobilephone() == null : this.getMobilephone().equals(other.getMobilephone()))
&& (this.getEmail() == null ? other.getEmail() == null : this.getEmail().equals(other.getEmail()))
&& (this.getBirthday() == null ? other.getBirthday() == null : this.getBirthday().equals(other.getBirthday()))
&& (this.getGender() == null ? other.getGender() == null : this.getGender().equals(other.getGender()));
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((getUserId() == null) ? 0 : getUserId().hashCode());
result = prime * result + ((getUserName() == null) ? 0 : getUserName().hashCode());
result = prime * result + ((getIntroduce() == null) ? 0 : getIntroduce().hashCode());
result = prime * result + ((getMobilephone() == null) ? 0 : getMobilephone().hashCode());
result = prime * result + ((getEmail() == null) ? 0 : getEmail().hashCode());
result = prime * result + ((getBirthday() == null) ? 0 : getBirthday().hashCode());
result = prime * result + ((getGender() == null) ? 0 : getGender().hashCode());
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(",userId=").append(userId);
sb.append(",userName=").append(userName);
sb.append(",introduce=").append(introduce);
sb.append(",mobilephone=").append(mobilephone);
sb.append(",email=").append(email);
sb.append(",birthday=").append(birthday);
sb.append(",gender=").append(gender);
sb.append(",serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
2. 使用者Mapper檔案
<?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.gavinbj.confmng.persistence.mapper.UserInfoMapper">
<resultMap id="BaseResultMap" type="com.gavinbj.confmng.persistence.entity.UserInfo">
<id column="user_id" jdbcType="VARCHAR" property="userId" />
<result column="user_name" jdbcType="VARCHAR" property="userName" />
<result column="introduce" jdbcType="VARCHAR" property="introduce" />
<result column="mobilephone" jdbcType="VARCHAR" property="mobilephone" />
<result column="email" jdbcType="VARCHAR" property="email" />
<result column="birthday" jdbcType="DATE" property="birthday" />
<result column="gender" jdbcType="VARCHAR" property="gender" />
</resultMap>
<sql id="Example_Where_Clause">
<where>
<foreach collection="oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Update_By_Example_Where_Clause">
<where>
<foreach collection="example.oredCriteria" item="criteria" separator="or">
<if test="criteria.valid">
<trim prefix="(" prefixOverrides="and" suffix=")">
<foreach collection="criteria.criteria" item="criterion">
<choose>
<when test="criterion.noValue">
and ${criterion.condition}
</when>
<when test="criterion.singleValue">
and ${criterion.condition} #{criterion.value}
</when>
<when test="criterion.betweenValue">
and ${criterion.condition} #{criterion.value} and #{criterion.secondValue}
</when>
<when test="criterion.listValue">
and ${criterion.condition}
<foreach close=")" collection="criterion.value" item="listItem" open="(" separator=",">
#{listItem}
</foreach>
</when>
</choose>
</foreach>
</trim>
</if>
</foreach>
</where>
</sql>
<sql id="Base_Column_List">
user_id,user_name,introduce,mobilephone,email,birthday,gender
</sql>
<select id="selectByExample" parameterType="com.gavinbj.confmng.persistence.entity.UserInfoExample" resultMap="BaseResultMap">
select
<if test="distinct">
distinct
</if>
<include refid="Base_Column_List" />
from user_info
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
<if test="orderByClause != null">
order by ${orderByClause}
</if>
<if test="limit != null">
<if test="offset != null">
limit ${offset},${limit}
</if>
<if test="offset == null">
limit ${limit}
</if>
</if>
</select>
<select id="selectByPrimaryKey" parameterType="java.lang.String" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user_info
where user_id = #{userId,jdbcType=VARCHAR}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.String">
delete from user_info
where user_id = #{userId,jdbcType=VARCHAR}
</delete>
<delete id="deleteByExample" parameterType="com.gavinbj.confmng.persistence.entity.UserInfoExample">
delete from user_info
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</delete>
<insert id="insert" parameterType="com.gavinbj.confmng.persistence.entity.UserInfo">
insert into user_info (user_id,gender)
values (#{userId,jdbcType=VARCHAR},#{userName,#{introduce,#{mobilephone,#{email,#{birthday,jdbcType=DATE},#{gender,jdbcType=VARCHAR})
</insert>
<insert id="insertSelective" parameterType="com.gavinbj.confmng.persistence.entity.UserInfo">
insert into user_info
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="userId != null">
user_id,</if>
<if test="userName != null">
user_name,</if>
<if test="introduce != null">
introduce,</if>
<if test="mobilephone != null">
mobilephone,</if>
<if test="email != null">
email,</if>
<if test="birthday != null">
birthday,</if>
<if test="gender != null">
gender,</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides=",">
<if test="userId != null">
#{userId,</if>
<if test="userName != null">
#{userName,</if>
<if test="introduce != null">
#{introduce,</if>
<if test="mobilephone != null">
#{mobilephone,</if>
<if test="email != null">
#{email,</if>
<if test="birthday != null">
#{birthday,</if>
<if test="gender != null">
#{gender,</if>
</trim>
</insert>
<select id="countByExample" parameterType="com.gavinbj.confmng.persistence.entity.UserInfoExample" resultType="java.lang.Long">
select count(*) from user_info
<if test="_parameter != null">
<include refid="Example_Where_Clause" />
</if>
</select>
<update id="updateByExampleSelective" parameterType="map">
update user_info
<set>
<if test="record.userId != null">
user_id = #{record.userId,</if>
<if test="record.userName != null">
user_name = #{record.userName,</if>
<if test="record.introduce != null">
introduce = #{record.introduce,</if>
<if test="record.mobilephone != null">
mobilephone = #{record.mobilephone,</if>
<if test="record.email != null">
email = #{record.email,</if>
<if test="record.birthday != null">
birthday = #{record.birthday,</if>
<if test="record.gender != null">
gender = #{record.gender,</if>
</set>
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByExample" parameterType="map">
update user_info
set user_id = #{record.userId,user_name = #{record.userName,introduce = #{record.introduce,mobilephone = #{record.mobilephone,email = #{record.email,birthday = #{record.birthday,gender = #{record.gender,jdbcType=VARCHAR}
<if test="_parameter != null">
<include refid="Update_By_Example_Where_Clause" />
</if>
</update>
<update id="updateByPrimaryKeySelective" parameterType="com.gavinbj.confmng.persistence.entity.UserInfo">
update user_info
<set>
<if test="userName != null">
user_name = #{userName,</if>
<if test="introduce != null">
introduce = #{introduce,</if>
<if test="mobilephone != null">
mobilephone = #{mobilephone,</if>
<if test="email != null">
email = #{email,</if>
<if test="birthday != null">
birthday = #{birthday,</if>
<if test="gender != null">
gender = #{gender,</if>
</set>
where user_id = #{userId,jdbcType=VARCHAR}
</update>
<update id="updateByPrimaryKey" parameterType="com.gavinbj.confmng.persistence.entity.UserInfo">
update user_info
set user_name = #{userName,introduce = #{introduce,mobilephone = #{mobilephone,email = #{email,birthday = #{birthday,gender = #{gender,jdbcType=VARCHAR}
where user_id = #{userId,jdbcType=VARCHAR}
</update>
</mapper>
3. Mapper檔案
package com.gavinbj.confmng.persistence.mapper;
import java.io.Serializable;
import java.util.List;
import org.apache.ibatis.annotations.Param;
/**
* DAO公共基類,由MybatisGenerator自動生成請勿修改
* @param <Model> The Model Class 這裡是泛型不是Model類
* @param <PK> The Primary Key Class 如果是無主鍵,則可以用Model來跳過,如果是多主鍵則是Key類
* @param <E> The Example Class
*/
public interface MyBatisBaseDao<Model,PK extends Serializable,E> {
long countByExample(E example);
int deleteByExample(E example);
int deleteByPrimaryKey(PK id);
int insert(Model record);
int insertSelective(Model record);
List<Model> selectByExample(E example);
Model selectByPrimaryKey(PK id);
int updateByExampleSelective(@Param("record") Model record,@Param("example") E example);
int updateByExample(@Param("record") Model record,@Param("example") E example);
int updateByPrimaryKeySelective(Model record);
int updateByPrimaryKey(Model record);
}
package com.gavinbj.confmng.persistence.mapper;
import com.gavinbj.confmng.persistence.entity.UserInfo;
import com.gavinbj.confmng.persistence.entity.UserInfoExample;
import org.springframework.stereotype.Repository;
/**
* UserInfoMapper繼承基類
*/
@Repository
public interface UserInfoMapper extends MyBatisBaseDao<UserInfo,String,UserInfoExample> {
}
6.2.4 使用MyBatis介面
1. @MapperScan掃描載入MyBaits的Mapper
package com.gavinbj.confmng;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @SpringBootApplication 標註這是SpringBoot專案的主程式類
*/
@MapperScan("com.gavinbj.confmng.persistence.mapper")
@SpringBootApplication
public class ConfManageApplication {
public static void main(String[] args) {
SpringApplication.run(ConfManageApplication.class,args);
}
}
2. UserInfoService & UserInfoServiceImpl
package com.gavinbj.confmng.service;
import java.util.List;
import com.gavinbj.confmng.persistence.entity.UserInfo;
/**
* 使用者資訊
*
* @author gavinbj
*
*/
public interface UserInfoService {
public UserInfo getUserByPK(String userId);
public List<UserInfo> selectUserInfos(String userName);
}
package com.gavinbj.confmng.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import com.gavinbj.confmng.persistence.entity.UserInfo;
import com.gavinbj.confmng.persistence.entity.UserInfoExample;
import com.gavinbj.confmng.persistence.mapper.UserInfoMapper;
import com.gavinbj.confmng.service.UserInfoService;
/**
* 使用者資訊
*
* @author gavinbj
*
*/
@Service
public class UserInfoServiceImpl implements UserInfoService {
@Autowired
private UserInfoMapper userInfoMapper;
/**
* 根據使用者ID進行主鍵檢索
*/
@Override
public UserInfo getUserByPK(String userId) {
return this.userInfoMapper.selectByPrimaryKey(userId);
}
/**
* 根據使用者名稱模糊檢索
*
*/
@Override
public List<UserInfo> selectUserInfos(String userName) {
UserInfoExample userExample = new UserInfoExample();
userExample.createCriteria().andUserNameLike(userName);
return this.userInfoMapper.selectByExample(userExample);
}
}
3. Mybatis的Example用法介紹
Example類用來構建一個動態的where子句,根據資料表中的每個非BLOB列可以被包括在where子句中。Example類包含一個內部靜態類Criteria以及包含一個用where子句中的條件列表。
建立Criteria物件可以使用Example類中的createCriteria()或者 or() 。使用createCriteria() 建立的Criteria ,它會自動為List屬性新增一個Criteria物件,這使得它更容易寫一個簡單的where子句。
Criteria 內部類的每個屬性都包含 andXXX 方法,以及如下的標準的SQL查詢方法:
IS NULL - 指相關的列必須為NULL
IS NOT NULL - 指相關的列必須不為NULL
= (equal) - 指相關的列必須等於方法引數中的值
<> (not equal) - 指相關的列必須不等於方法引數中的值
(greater than) - 指相關的列必須大於方法引數中的值
= (greater than or equal) - 指相關的列必須大於等於方法引數中的值
< (less than) - 指相關的列必須小於於方法引數中的值
<= (less than or equal) - 指相關的列必須小於等於方法引數中的值
LIKE - 指相關的列必須 “like” 方法引數中的值. 這個方法不用必須加入 ‘%’,您必須設定方法引數中的值.
NOT LIKE - 指相關的列必須 “not like” 方法引數中的值. 這個方法不用必須加入 ‘%’,您必須設定方法引數中的值.
BETWEEN - 指相關的列必須在 “between” 方法引數中的兩個值之間.
NOT BETWEEN - 指相關的列必須不在 “not between” 方法引數中的兩個值之間.
IN - 指相關的列必須在傳入的方法引數的list中.
NOT IN - 指相關的列必須不在傳入的方法引數的list中.
4. 建立REST測試介面
package com.gavinbj.confmng.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.gavinbj.common.bean.BaseResult;
import com.gavinbj.common.bean.ResponseUtils;
import com.gavinbj.confmng.persistence.entity.UserInfo;
import com.gavinbj.confmng.service.UserInfoService;
@RestController
@RequestMapping("/api/user")
public class UserController {
@Autowired
UserInfoService userInfoService;
/**
* 根據使用者名稱進行模糊檢索
*
*/
@GetMapping("/users")
public BaseResult<List<UserInfo>> searchUsers(@RequestParam(value = "userName",required = true) String userName) {
List<UserInfo> lstUsers = this.userInfoService.selectUserInfos(userName);
return ResponseUtils.makeOKRsp(lstUsers);
}
/**
* 檢索使用者資訊
*
*/
@GetMapping("/users/{userId}")
public BaseResult<UserInfo> getUserById(@PathVariable("userId") String userId) {
UserInfo userInfo = userInfoService.getUserByPK(userId);
return ResponseUtils.makeOKRsp(userInfo);
}
}
驗證測試結果如下:
{
"status": 0,"code": 1003,"msg": "處理成功!","data": {
"userId": "gavin","userName": "蓋文","introduce": "大學教授","mobilephone": "13940981276","email": "[email protected]","birthday": "2019-10-07T00:00:00.000+0000","gender": "男"
}
}