一、先创建一个表
CREATE TABLE users (
`id` INT ( 11 ) NOT NULL AUTO_INCREMENT,
`username` VARCHAR ( 255 ) DEFAULT NULL,
`password` VARCHAR ( 255 ) DEFAULT NULL,
`name` VARCHAR ( 255 ) DEFAULT NULL,
PRIMARY KEY ( `id` )
) ENGINE = MyISAM AUTO_INCREMENT = 1247 DEFAULT CHARSET = utf8;
二、Spring Boot 整合 MyBatis 流程
springboot里面mybatis流程图
三、例子
1. 创建一个SpringBoot项目
2. 修改pom.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.7</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>cn.lazyfennec</groupId>
<artifactId>springboot-mybatis</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-mybatis</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- MyBatis 依赖引入 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
<!-- MySQL驱动引入-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
3. 修改application.properties
# MySql配置
spring.datasource.url=jdbc:mysql://localhost:3306/cloud_study?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
spring.datasource.username=#### 替换账号
spring.datasource.password=#### 替换密码
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
# MyBatis配置
# 设置配置文件路径,默认在resources的目录
mybatis.config-location=classpath:mybatis/mybatis-config.xml
# 设置mapper映射文件路径,默认在resources的目录
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
# 设置项目中实体类的包路径
mybatis.type-aliases-package=cn.lazyfennec.springboot.entity
# 日志打印
# 展示sql语句, DEBUG等级
logging.level.cn.lazyfennec.springboot.repository.UsersDao=debug
4. 创建Users实体类
- 在cn.lazyfennec.springboot下创建entity文件夹
- 在cn.lazyfennec.springboot.entity下创建Users
package cn.lazyfennec.springboot.entity;
/**
* @Author: Neco
* @Description:
* @Date: create in 2022/4/27 22:52
*/
public class Users {
private String id;
private String username;
private String password;
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Users{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
", name='" + name + '\'' +
'}';
}
}
5. 创建UsersDao
- 在cn.lazyfennec.springboot下创建repository文件夹
- 在cn.lazyfennec.springboot.repository 下创建UsersDao
package cn.lazyfennec.springboot.repository;
import cn.lazyfennec.springboot.entity.Users;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UsersDao {
List<Users> findAll();
Users findById(Integer id);
@Select("select id, username, password, name from users where name like concat('%', #{name}, '%')")
List<Users> findByName(String name);
}
6. 创建mybatis-config.xml
- 在resources下创建mybatis文件夹
- 在mybatis文件夹下创建mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
</configuration>
7. 创建UsersMapper.xml
- 在resources/mybatis下创建mapper文件夹
- 在resources/mybatis/mapper下创建UsersMapper.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="cn.lazyfennec.springboot.repository.UsersDao">
<select id="findAll" resultType="Users">
select id, username, password, name from users
</select>
<select id="findById" resultType="Users">
select id, username, password, name from users where id = #{id}
</select>
</mapper>
8. 在XXXApplication.java上添加@MapperScan
- 在SpringbootMybatisApplication类上添加@MapperScan
package cn.lazyfennec.springboot;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@MapperScan("cn.lazyfennec.springboot.repository")
@SpringBootApplication
public class SpringbootMybatisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootMybatisApplication.class, args);
}
}
9. 修改并启动测试类
package cn.lazyfennec.springboot;
import cn.lazyfennec.springboot.repository.UsersDao;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
@SpringBootTest
class SpringbootMybatisApplicationTests {
@Resource
private UsersDao usersDao;
@Test
void contextLoads() {
System.out.println(usersDao.findAll());
System.out.println("------------------------------");
System.out.println(usersDao.findById(1));
System.out.println("------------------------------");
System.out.println(usersDao.findByName("德"));
}
}
10. 运行结果
2022-04-27 23:22:25.738 DEBUG 17420 --- [ main] c.l.s.repository.UsersDao.findAll : ==> Preparing: select id, username, password, name from users
2022-04-27 23:22:25.763 DEBUG 17420 --- [ main] c.l.s.repository.UsersDao.findAll : ==> Parameters:
2022-04-27 23:22:25.783 DEBUG 17420 --- [ main] c.l.s.repository.UsersDao.findAll : <== Total: 2
[Users{id='1', username='liudehua', password='123456', name='刘德华'}, Users{id='2', username='zhangxueyou', password='123456', name='张学友'}]
------------------------------
2022-04-27 23:22:25.789 DEBUG 17420 --- [ main] c.l.s.repository.UsersDao.findById : ==> Preparing: select id, username, password, name from users where id = ?
2022-04-27 23:22:25.789 DEBUG 17420 --- [ main] c.l.s.repository.UsersDao.findById : ==> Parameters: 1(Integer)
2022-04-27 23:22:25.790 DEBUG 17420 --- [ main] c.l.s.repository.UsersDao.findById : <== Total: 1
Users{id='1', username='liudehua', password='123456', name='刘德华'}
------------------------------
2022-04-27 23:22:25.791 DEBUG 17420 --- [ main] c.l.s.repository.UsersDao.findByName : ==> Preparing: select id, username, password, name from users where name like concat('%', ?, '%')
2022-04-27 23:22:25.791 DEBUG 17420 --- [ main] c.l.s.repository.UsersDao.findByName : ==> Parameters: 德(String)
2022-04-27 23:22:25.801 DEBUG 17420 --- [ main] c.l.s.repository.UsersDao.findByName : <== Total: 1
[Users{id='1', username='liudehua', password='123456', name='刘德华'}]
2022-04-27 23:22:25.822 INFO 17420 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown initiated...
2022-04-27 23:22:25.825 INFO 17420 --- [ionShutdownHook] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Shutdown completed.
Process finished with exit code 0
11. 其他内容
- mybatis-config.xml 可以不用创建
- 可以删除mybatis-config.xml
- 顺带删除或注释掉application.properties 中的
# 设置配置文件路径,默认在resources的目录
mybatis.config-location=classpath:mybatis/mybatis-config.xml
- 如果不需要使用xml来实现配置查询语句,则可以删除UsersMapper.xml
- 如果仅用注解来配置SQL语句,则可以删除UsersMapper.xml
- 如果都不需要xxxMapper.xml,则可以顺带删除或注释掉application.properties中的
# 设置mapper映射文件路径,默认在resources的目录
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
- 如果xxxMapper.xml中用的是全路径类名,或不适用xxxMapper.xml,则可以删除别名的配置
- 这种情况下可以删除或注释掉application.properties中的
# 设置项目中实体类的包路径
mybatis.type-aliases-package=cn.lazyfennec.springboot.entity
- 注:以上的application.properties如果是换成yml文件同样适用
网友评论