文章目录
Spring整合Mybatis框架-基于纯配置类+注解
本案例环境
- JDK 17
- Spring6
- Mybatis3
- Maven3.6.1
- mysql 8.0.33
- druid 1.2.22
步骤
- 准备数据库表
- 创建一个Maven项目
- 引入依赖
- 创建包结构
- 编写配置类
- 编写业务代码
- 测试
1.准备数据库表
该表结构比较简单,包括汽车编号,汽车名称和汽车价格
# 创建数据库
create database if not exists mybatis_spring;
# 使用数据库
use mybatis_spring;
# 创建数据库表
create table if not exists car(
id bigint primary key auto_increment comment '汽车编号',
car_name varchar(255) comment '汽车名称',
car_price double comment '汽车价格'
) COMMENT '汽车表';
# 插入测试数据
insert into car(car_name,car_price) value('丰田',20),('奔驰',50);
2. 创建Maven项目
3.在pom.xml中引入依赖,打包一套带走
<dependencies>
<!-- spring核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>6.1.4</version>
</dependency>
<!-- mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.33</version>
</dependency>
<!-- mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.10</version>
</dependency>
<!-- spring整合mybatis,里面包含了核心对象 SqlSessionFactoryBean-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>3.0.3</version>
</dependency>
<!-- 连接数据库依赖-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.1.4</version>
</dependency>
<!-- 事务相关,比如@Transational注解-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>6.1.4</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.22</version>
</dependency>
<!-- =======================上面的依赖为spring整合mybatis必备的依赖============================-->
<!-- ==================spring整合junit5 start =================-->
<!-- junit5单元测试-->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>6.1.4</version>
</dependency>
<!-- ==================spring整合junit end =================-->
</dependencies>
4.创建包结构
5.编写配置类
- 创建SpringConfig配置类
@Configuration //标识配置类
@ComponentScan("com.xxin") //包组件扫描,这里扫描com.xxin包及其子包下的所有类
public class SpringConfig {
}
- 创建MybatisConfig配置类
/**
* @author 小欣
* @version 1.0
* @since 1.8
*/
@Configuration
@PropertySource("classpath:jdbc.properties") //导入类路径下的jdbc.properties配置类
@MapperScan("com.xxin.mapper") //mapper接口扫描
@EnableTransactionManagement //启用事务注解
public class MybatisConfig {
@Value("${jdbc.driver}")
private String driverClassName;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
/**
* 配置数据源
* @return
*/
@Bean
public DataSource dataSource(){
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setDriverClassName(driverClassName);
druidDataSource.setUrl(url);
druidDataSource.setUsername(username);
druidDataSource.setPassword(password);
return druidDataSource;
}
//Mybatis-spring核心类创建
@Bean
public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource){
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource);
try {
//指定mapper映射文件的路径
sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("/mapper/**.xml"));
} catch (IOException e) {
e.printStackTrace();
}
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
//configuration对象可以用来配置mybatis核心配置文件中settings标签中的配置,想配置什么就使用该类
configuration.setMapUnderscoreToCamelCase(true); //驼峰自动映射
sqlSessionFactoryBean.setConfiguration(configuration);
return sqlSessionFactoryBean;
}
//配置事务管理器
@Bean
public TransactionManager transactionManager(DataSource dataSource){
JdbcTransactionManager jdbcTransactionManager = new JdbcTransactionManager();
jdbcTransactionManager.setDataSource(dataSource);
return jdbcTransactionManager;
}
}
- 创建jdbc.properties配置文件
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis_spring
jdbc.username=root
jdbc.password=root
#将连接数据库的信息改成你自己的
6.编写业务代码
1.创建实体类接收数据
Car
/**
* @author 小欣
* @version 1.0
* @since 1.8
*/
public class Car {
private Long id;
private String carName;
private Double carPrice;
public Car() {
}
public Car(Long id, String carName, Double carPrice) {
this.id = id;
this.carName = carName;
this.carPrice = carPrice;
}
/**
* 获取
* @return id
*/
public Long getId() {
return id;
}
/**
* 设置
* @param id
*/
public void setId(Long id) {
this.id = id;
}
/**
* 获取
* @return carName
*/
public String getCarName() {
return carName;
}
/**
* 设置
* @param carName
*/
public void setCarName(String carName) {
this.carName = carName;
}
/**
* 获取
* @return carPrice
*/
public Double getCarPrice() {
return carPrice;
}
/**
* 设置
* @param carPrice
*/
public void setCarPrice(Double carPrice) {
this.carPrice = carPrice;
}
public String toString() {
return "Car{id = " + id + ", carName = " + carName + ", carPrice = " + carPrice + "}";
}
}
2.创建CarMapper接口
public interface CarMapper {
/**
* 查询所有汽车信息
* @return 汽车信息集合
*/
List<Car> getCarList();
}
3.创建CarMapper.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.xxin.mapper.CarMapper">
<select id="getCarList" resultType="com.xxin.pojo.Car">
select * from car
</select>
</mapper>
7.测试
这里使用Spring整合Junit5进行单元测试
@ExtendWith(SpringExtension.class) //固定写法,Spring集成Junit5核心类
@ContextConfiguration(classes = SpringConfig.class) //绑定Spring配置类,初始化Spring上下文
class CarMapperTest {
@Autowired
private CarMapper carMapper;
@Test
void getCarList() {
//这里测试用到了jdk8的新特性:Optiaonl工具类、lambda表达式、方法引用,你也可以使用自己的方式进行测试
Optional.ofNullable(carMapper.getCarList()).ifPresentOrElse(cars -> cars.forEach(System.out::println),() -> System.out.println("未查询到数据"));
}
}
测试结果
Car{id = 1, carName = 丰田, carPrice = 20.0}
Car{id = 2, carName = 奔驰, carPrice = 50.0}