環(huán)境
- Mac OS 10.13
- Mybatis3.4 [org.mybatis.spring.boot 2.0.1]
- MySQL 8.0.16
- JAVA 11
- SpringBoot 2.1.1.RELEASE
配置MySQL
1. 接入依賴
在 pom.xml 文件中添加一下依賴灾锯,用于接入JDBC驅(qū)動(dòng)
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
2. 配置 aplication.properties
在該配置文件下瓤摧,添加以下代碼:
#設(shè)置數(shù)據(jù)庫海蔽,使用com.mysql.cj.jdbc.Driver對(duì)應(yīng)mysql6以上版本,com.mysql.jdbc.Driver對(duì)應(yīng)mysql5一下版本
spring.datasource.driver-class-name= com.mysql.cj.jdbc.Driver
spring.datasource.url= jdbc:mysql://localhost:3306/數(shù)據(jù)庫名稱?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true
spring.datasource.username = 用戶名
spring.datasource.password = 密碼
據(jù)查找資料說:
使用com.mysql.cj.jdbc.Driver需要設(shè)置一下時(shí)區(qū)腺劣,但是貌似沒有遇到這個(gè)坑。
另外的方法:據(jù)資料介紹秒拔,還可以在mybatis_config.xml文件中根據(jù)不同環(huán)境配置不同的數(shù)據(jù)庫础倍,例如以下代碼:
<!--不同環(huán)境數(shù)據(jù)庫源配置,默認(rèn)是dev環(huán)境-->
<environments default="dev">
<!--開發(fā)環(huán)境-->
<environment id="dev">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/數(shù)據(jù)庫名稱?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true"/>
<property name="username" value="用戶名"/>
<property name="password" value="密碼"/>
</dataSource>
</environment>
<!--生產(chǎn)環(huán)境-->
<environment id="prod">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://遠(yuǎn)程數(shù)據(jù)庫服務(wù)設(shè)備ip/數(shù)據(jù)庫?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true"/>
<property name="username" value="用戶名"/>
<property name="password" value="密碼"/>
</dataSource>
</environment>
</environments>
不過很不幸的是徒蟆,這個(gè)配置好像無效戈抄。目前采用第一種方法,個(gè)人建議第二種后专,便于管理,將來有機(jī)會(huì)再查證無效的具體原因输莺。
配置Mybatis
1.接入依賴
在 pom.xml 文件中添加一下依賴戚哎,用于接入Mybatis庫
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
2.配置 aplication.properties
在這之前裸诽,你需要在resources文件夾下,新建mybatis-config.xml文件型凳,用于添加mybatis的配置丈冬,本人工程中該文件的目錄是resources/mybatis/config/mybatis-config.xml。
另外甘畅,mybatis需要許多mapper文件埂蕊,所以先創(chuàng)建一個(gè)mapper文件夾,以便將來能用疏唾,本人工程中該文件夾目錄是resources/mybatis/mapper蓄氧。
然后引入配置和mapper文件:
mybatis.check-config-location=true
mybatis.config-location=classpath:mybatis/config/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
3.配置mybatis-config.xml
<configuration>
<!--加載所有entity實(shí)體類-->
<typeAliases>
<package name="com.xxx.xxxx.entity"/>
</typeAliases>
</configuration>
目前還沒有對(duì)mybatis做過多的配置,而只是通過package的方式槐脏,加載所有entity實(shí)體類喉童。(接下來要介紹的User.class就是在該entity文件夾下)
4.創(chuàng)建實(shí)體對(duì)象(entity)
在com.xxx.xxxx.entity*文件夾中,新增User.class文件顿天,內(nèi)容如下:
package com.xxx.xxxx.entity;
import java.sql.Timestamp;
import java.util.Date;
public class User{
private String username;
private String email;
private String password;
private int sex;
private Date birthday;
private String headPhoto;
private String phone;
private Timestamp createTime;
public String getUsername(){
return username;
}
public void setUsername(String username){
this.username = username;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email = email;
}
public String getPassword(){
return password;
}
public void setPassword(String password){
this.password = password;
}
public int getSex(){ return sex; }
public void setSex(int sex){ this.sex = sex; }
public Date getBirthday(){ return birthday; }
public void setBirthday(Date birthday){ this.birthday = birthday; }
public String getHeadPhoto(){ return headPhoto; }
public void setHeadPhoto(String headPhoto){ this.headPhoto = headPhoto; }
public String getPhone(){ return phone; }
public void setPhone(String phone){ this.phone = phone; }
public Timestamp getCreateTime(){
return createTime;
}
public void setCreateTime(Timestamp createTime){
this.createTime = createTime;
}
}
然后創(chuàng)建數(shù)據(jù)庫表user,表列如下:
user_id varchar(64) PK
email varchar(255)
username varchar(16)
password varchar(32)
create_time timestamp
sex int(11)
birthday date
headphoto varchar(200)
phone varchar(20)
5.創(chuàng)建Respository接口
在mybatis中堂氯,我們需要實(shí)現(xiàn)查詢,刪除牌废,更新等操作咽白,所有的這些操作都在mapper.xml文件中實(shí)現(xiàn),我們只需要給項(xiàng)目暴露接口函數(shù)就好了鸟缕。我們把這些接口全部歸類到respository文件夾下晶框。例如,我們需要對(duì)user進(jìn)行一些查詢操作叁扫,你可以編寫以下接口:
IUserMapper.class
import com.xxx.xxxx.entity.User;
public interface IUserMapper {
//通過userId去獲取用戶信息
public User getUserById(String userId);
}
6.接口實(shí)現(xiàn)Mapper.xml
我們需要實(shí)現(xiàn)getUserById操作三妈。首先我們得在,mapper文件夾下創(chuàng)建一個(gè)UserMapper.xml文件莫绣,文件內(nèi)容如下:
<?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.xxx.xxx.respository.IUserMapper">
<resultMap id="UserMapperResult" type="com.xxx.xxxx.entity.User">
<result property="email" column="email"></result>
<result property="username" column="username"></result>
<result property="sex" column="sex"></result>
<result property="birthday" column="birthday"></result>
<result property="headPhoto" column="head_photo"></result>
<result property="phone" column="phone"></result>
<result property="password" column="password"></result>
<result property="createTime" column="create_time"></result>
</resultMap>
<select id="getUserById" resultMap="UserMapperResult">
select * from user
where
user.user_id = #{userId}
</select>
</mapper>
請(qǐng)留意這行<mapper namespace="com.xxx.xxxx.respository.IUserMapper">
畴蒲,這里直接關(guān)聯(lián)到了IUserMapper,然后對(duì)應(yīng)的接口函數(shù)getUserById对室,也在這里做了映射<select id="getUserById" resultMap="UserMapperResult">
模燥。
7.暴露接口給mybatis
在接口與mapper.xml文件關(guān)聯(lián)起來之前,我們要先把接口文件暴露給mybatis掩宜。而mybatis通過注解 @MapperScan 來掃描這些接口文件蔫骂,在本人工程中,我們?cè)赼pplication文件中添加了@MapperScan("com.xxx.xxxx.respository")
代碼牺汤,這樣mybatis就會(huì)自動(dòng)掃描respository文件夾下的所有接口了辽旋。
xxxApplication.class
package com.xxx.xxxx;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("com.xxx.xxxx.respository")
@SpringBootApplication
public class xxxApplication {
public static void main(String[] args) {
SpringApplication.run(xxxApplication.class, args);
}
}
8.調(diào)用
在本人工程中,有一個(gè)loginController.class,里面實(shí)現(xiàn)了get請(qǐng)求补胚,另外通過@Autowired的方式注入IUserMapper的bean码耐。
LoginController.class
package com.xxx.xxxx.controllers.Login;
import com.xxx.xxxx.entity.User;
import com.xxx.xxxx.respository.IUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping(value = "/login")
public class LoginController {
@Autowired
private IUserMapper userMapper;
@RequestMapping(value = "/get" , method = RequestMethod.GET)
public User loginGet(){
System.out.println("get 方法=====");
User user = userMapper.getUserById("32435cdsg");
return user;
}
}
9.結(jié)果如下
{
"username":"xxxxxx",
"email":"xxx@email.com",
"password":"xxxxx","sex":0,
"birthday":null,
"headPhoto":null,
"phone":null,
"createTime":"2019-07-11T22:27:59.000+0000"
}