天天看点

5.集成持久层框架MyBatis

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”,可以查询到相应的信息,测试结果如下图所示。

5.集成持久层框架MyBatis