SpringBoot 项目整合 MyBatis 框架,附带测试示例
以下是整合MyBatis框架的核心步骤和示例代码:
- 添加MyBatis依赖到
pom.xml
文件中:
<dependencies>
<!-- 添加MyBatis依赖 -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<!-- 添加数据库驱动依赖,以MySQL为例 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.23</version>
</dependency>
</dependencies>
- 配置数据库信息和MyBatis在
application.properties
或application.yml
文件中:
# application.properties 示例
spring.datasource.url=jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- 创建Mapper接口和Mapper XML文件:
// UserMapper.java
package com.example.mapper;
public interface UserMapper {
User selectUserById(int id);
}
<!-- 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.example.mapper.UserMapper">
<select id="selectUserById" parameterType="int" resultType="com.example.model.User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
- 在SpringBoot启动类上添加Mapper扫描注解:
// YourApplication.java
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mapper")
public class YourApplication {
public static void main(String[] args) {
SpringApplication.run(YourApplication.class, args);
}
}
- 创建Service和Service实现类:
// UserService.java
package com.example.service;
public interface UserService {
User getUserById(int id);
}
// UserServiceImpl.java
package com.example.service;
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public User getUserById(int id) {
return userMapper.selectUserById(id);
}
}
- 创建Controller进行测
评论已关闭