springboot如何集成MyBatis实现增删改查
时间: 2024-01-23 18:03:15 浏览: 96
1. 添加MyBatis和MyBatis-SpringBoot-Starter依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
```
2. 配置数据源
在application.properties或application.yml中配置数据源信息,如:
```
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=root
```
3. 创建实体类和Mapper接口
创建实体类和对应的Mapper接口,如:
```
public class User {
private Long id;
private String username;
private String password;
// getter and setter
}
public interface UserMapper {
List<User> findAll();
User findById(Long id);
void insert(User user);
void update(User user);
void delete(Long id);
}
```
4. 创建Mapper XML文件
在resources目录下创建Mapper XML文件,定义SQL语句,如:
```
<?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">
<resultMap id="BaseResultMap" type="com.example.model.User">
<id column="id" property="id" />
<result column="username" property="username" />
<result column="password" property="password" />
</resultMap>
<select id="findAll" resultMap="BaseResultMap">
SELECT * FROM user
</select>
<select id="findById" resultMap="BaseResultMap">
SELECT * FROM user WHERE id=#{id}
</select>
<insert id="insert">
INSERT INTO user (username, password) VALUES (#{username}, #{password})
</insert>
<update id="update">
UPDATE user SET username=#{username}, password=#{password} WHERE id=#{id}
</update>
<delete id="delete">
DELETE FROM user WHERE id=#{id}
</delete>
</mapper>
```
5. 注册Mapper
在Spring Boot中,可以使用@MapperScan注解扫描Mapper接口,并自动注册到Spring容器中,如:
```
@SpringBootApplication
@MapperScan("com.example.mapper")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
6. 调用Mapper方法
在Service或Controller中注入Mapper,并调用Mapper方法,如:
```
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> findAll() {
return userMapper.findAll();
}
public User findById(Long id) {
return userMapper.findById(id);
}
public void insert(User user) {
userMapper.insert(user);
}
public void update(User user) {
userMapper.update(user);
}
public void delete(Long id) {
userMapper.delete(id);
}
}
```
以上就是使用Spring Boot集成MyBatis实现增删改查的步骤。
阅读全文