SpringBoot整合Mybatis
搭建环境
。1.下载资源更快:https://start.aliyun.com/,如果选Default那么加载资源慢
2.选择要导入的依赖:Spring Web,MySQL Driver,JDBC API
3.pom.xml导入整合Mybatis的依赖
SpringBoot官方并没有提供如何整合,mybatis-spring-boot-starter是Mybatis官方提供的,其中还有对SpringBoot整合Mybatis的版本要求
<!--导入整合Mybatis的依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
<!--导入lombok的依赖:lombok快速生成set、get、无参构造、有参构造、toString(使用注解即可)-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
如果lombok注解不生效,可能是Lombok插件没有下载:settings---->plugins------>下图
4.编写实体类
User.java
package com.itheima.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class User {
private int id;
private String username;
private Date birthday;
private String sex;
private String address;
}
5.编写接口层(也叫dao层或者mapper层)
UserMapper.java
package com.itheima.mapper;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
//接口类,dao层
@Mapper//表示这个类是Mybatis的mapper.另外一种方式在启动类加注解@MapperScan
@Repository//接口层注解:
public interface UserMapper {
List<User> queryUser();
User queryUserById(int id);
int addUser(User user);
int updateUser(User user);
int deleteUser(int id);
}
6.编写UserMapper.xml
编写SQL 操作数据库有两种写法,一种是写一个xml配置文件映射到某个接口层;第二种是在接口层的类上加注解。这个案例是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.itheima.mapper.UserMapper">
<!--配置查询所有-->
<!--id为UserMapper方法的名称-->
<select id="queryUser" resultType="User">
select * from user;
</select>
</mapper>
项目结构:
7.编写Controller
SelectUserController.java
package com.itheima.controller;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class SelectUserController {
@Autowired
UserMapper userMapper;
@GetMapping("/selectUser")
public List<User> selectUser(){
List<User> userList = userMapper.queryUser();
return userList;
}
}
8.之前大部分都是为了验证Mybatis整合是否成功,但是SpringBoot整合Mybatis,要让Mybatis生效,还有下面这个重要步骤
在application.yaml(或application.properties)中设置数据库密码和整合Mybatis
spring:
datasource:
username: root
password: "123456"
url: jdbc:mysql://localhost:3306/eesy_mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
#SpringBoot整合mybatis
mybatis:
#设置返回值类型的别名
type-aliases-package: com.itheima.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
9.测试:
SpringBoot整合Mybatis成功