1.MyBatis簡介
MyBatis是一款優秀的資料持久層架構,它支援定制化SQL、存儲過程以及進階映射。其避免了JDBC一系列繁雜的操作過程,改用簡單的XML或注解來配置和映射原生資訊,将接口和Java的POJO類映射成資料庫中的記錄。
2.引入依賴
建立一個SpringBoot工程,并在pom.xml檔案中添加內建MyBatis所需要的dependency。
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<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.1.1</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<scope>provided</scope>
</dependency>
3.添加配置
在application.properties檔案中添加如下配置資訊。
############################################################
#
# MySQL配置
#
############################################################
### 連接配接資訊
spring.datasource.url = jdbc:mysql://localhost:3306/mydb
### 使用者名
spring.datasource.username = root
### 密碼
spring.datasource.password = admin123
### 驅動
spring.datasource.driver-class-name = com.mysql.cj.jdbc.Driver
############################################################
#
# MyBatis配置
#
############################################################
### po類存放目錄
mybatis.type-aliases-package = com.leichuangkj.mybatis.dao.po
### mapper(.xml)資源檔案存放路徑
mybatis.mapper-locations = classpath:mybatis/mapper/*.xml
4.開發服務端通用傳回對象
在項目目錄“/src/main/java/com/leichuangkj/mybatis”下建立common目錄,并在common目錄下建立ResponseCode枚舉類和ServerResponse類,具體代碼如下。
public enum ResponseCode {
//1.定義枚舉值
ERROR(0,"ERROR"),
SUCCESS(1,"SUCCESS");
//2.定義枚舉屬性
private final int code;
private final String desc;
//3.定義構造函數
ResponseCode(int code, String desc){
this.code = code;
this.desc = desc;
}
//4.定義get方法
public int getCode(){
return code;
}
public String getDesc(){
return desc;
}
}
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
//保證序列化json的時候,如果是null的對象,key也會消失
public class ServerResponse<T> implements Serializable {
//1.定義屬性
private int status;
private String message;
private T data;
//2.定義構造函數
private ServerResponse(int status) {
this.status = status;
}
private ServerResponse(int status, T data) {
this.status = status;
this.data = data;
}
private ServerResponse(int status, String message, T data) {
this.status = status;
this.message = message;
this.data = data;
}
private ServerResponse(int status, String message) {
this.status = status;
this.message = message;
}
//3.getter方法
public int getStatus() {
return status;
}
public T getData() {
return data;
}
public String getMessage() {
return message;
}
@JsonIgnore
//使之不在json序列化結果當中
//4.判斷這個響應是不是一個正确的響應
public boolean isSuccess() {
return this.status == ResponseCode.SUCCESS.getCode();
}
//5.定義傳回對象的方法
public static <T> ServerResponse<T> createBySuccess() {
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
}
public static <T> ServerResponse<T> createBySuccessMessage(String message) {
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), message);
}
public static <T> ServerResponse<T> createBySuccess(T data) {
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), data);
}
public static <T> ServerResponse<T> createBySuccess(String message, T data) {
return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(), message, data);
}
public static <T> ServerResponse<T> createByError() {
return new ServerResponse<T>(ResponseCode.ERROR.getCode(), ResponseCode.ERROR.getDesc());
}
public static <T> ServerResponse<T> createByErrorMessage(String errorMessage) {
return new ServerResponse<T>(ResponseCode.ERROR.getCode(), errorMessage);
}
public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode, String errorMessage) {
return new ServerResponse<T>(errorCode, errorMessage);
}
public static <T> ServerResponse<T> createByErrorCodeMessageData(int errorCode, String errorMessage,T data) {
return new ServerResponse<T>(errorCode, errorMessage,data);
}
}
5.dao層開發
首先在項目目錄“/src/main/java/com/leichuangkj/mybatis”下建立“/dao/po”目錄,并在po目錄下建立User實體類,具體代碼如下。
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class User {
private Integer id;
private String name;
private String email;
}
然後在dao目錄下建立mapper目錄,并在mapper目錄下建立UserMapper接口,具體代碼如下。
@Repository
public interface UserMapper {
User findByName(String id);
}
最後在resource目錄下建立“mybatis/mapper”目錄,并在mapper目錄下建立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.leichuangkj.mybatis.dao.mapper.UserMapper" >
<resultMap id="BaseResultMap" type="com.leichuangkj.mybatis.dao.po.User">
<constructor>
<idArg column="id" javaType="java.lang.Integer" jdbcType="INTEGER" />
<arg column="name" javaType="java.lang.String" jdbcType="VARCHAR" />
<arg column="email" javaType="java.lang.String" jdbcType="VARCHAR" />
</constructor>
</resultMap>
<select id="findByName" parameterType="java.lang.String" resultMap="BaseResultMap">
select id, name, email
from user
where name = #{name,jdbcType=VARCHAR}
</select>
</mapper>
6.service層開發
在項目目錄“/src/main/java/com/leichuangkj/mybatis”下建立service目錄,并在service目錄下建立IUser接口,具體代碼如下。
public interface IUser {
ServerResponse findByName(String name);
}
然後在service目錄下建立impl目錄,并在impl目錄下建立UserImpl實作類,具體代碼如下。
@Service
public class UserImpl implements IUser {
@Autowired
UserMapper userMapper;
@Override
public ServerResponse findByName(String name) {
User user = userMapper.findByName(name);
if(user == null){
return ServerResponse.createByErrorMessage("沒有查詢到使用者");
}
return ServerResponse.createBySuccess(user);
}
}
7.controller層開發
在項目目錄“/src/main/java/com/leichuangkj/mybatis”下建立controller目錄,并在controller目錄下建立UserController類,具體代碼如下。
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
UserImpl userImpl;
@RequestMapping(value = "/findByName",method = RequestMethod.POST)
@ResponseBody
public ServerResponse findByName(@RequestBody User user){
return userImpl.findByName(user.getName());
}
}
8.啟動項目
在啟動類MyBatisApplication上添加注解“@MapperScan(basePackages = “com.leichuangkj.mybatis.dao.mapper”)”,然後啟動項目。
@MapperScan(basePackages = "com.leichuangkj.mybatis.dao.mapper")
@SpringBootApplication
public class MyBatisApplication {
public static void main(String[] args) {
SpringApplication.run(MyBatisApplication.class, args);
}
}
9.測試
啟動項目,然後在postman中請求“http://localhost:8080/user/findByName”,可以查詢到相應的資訊,測試結果如下圖所示。
