返回
进阶!SpringBoot整合MyBatis之配置文件版
见解分享
2023-12-30 22:02:46
简介
在上一篇文章中,我们介绍了如何使用注解的方式将MyBatis整合到SpringBoot项目中。在本文中,我们将详细讲解如何使用配置文件的方式将MyBatis整合到SpringBoot项目中。
配置文件版MyBatis整合
1. 依赖引入
首先,我们需要在pom.xml文件中引入MyBatis的依赖。
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.9</version>
</dependency>
2. 配置数据源
接下来,我们需要在application.properties文件中配置数据源。
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8
spring.datasource.username=root
spring.datasource.password=123456
3. 配置MyBatis
然后,我们需要在application.properties文件中配置MyBatis。
mybatis.configuration.map-underscore-to-camel-case=true
4. 创建MyBatis配置文件
接下来,我们需要在resources目录下创建MyBatis配置文件。
<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/UserMapper.xml"/>
</mappers>
</configuration>
5. 创建Mapper接口
接下来,我们需要创建Mapper接口。
public interface UserMapper {
List<User> findAll();
User findById(Long id);
int insert(User user);
int update(User user);
int delete(Long id);
}
6. 创建Mapper实现类
接下来,我们需要创建Mapper实现类。
@Mapper
public class UserMapperImpl implements UserMapper {
@Autowired
private SqlSession sqlSession;
@Override
public List<User> findAll() {
return sqlSession.selectList("UserMapper.findAll");
}
@Override
public User findById(Long id) {
return sqlSession.selectOne("UserMapper.findById", id);
}
@Override
public int insert(User user) {
return sqlSession.insert("UserMapper.insert", user);
}
@Override
public int update(User user) {
return sqlSession.update("UserMapper.update", user);
}
@Override
public int delete(Long id) {
return sqlSession.delete("UserMapper.delete", id);
}
}
7. 使用MyBatis
最后,我们就可以在代码中使用MyBatis了。
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/findAll")
public List<User> findAll() {
return userMapper.findAll();
}
@GetMapping("/findById")
public User findById(Long id) {
return userMapper.findById(id);
}
@PostMapping("/insert")
public int insert(User user) {
return userMapper.insert(user);
}
@PutMapping("/update")
public int update(User user) {
return userMapper.update(user);
}
@DeleteMapping("/delete")
public int delete(Long id) {
return userMapper.delete(id);
}
}
总结
以上就是如何使用配置文件的方式将MyBatis整合到SpringBoot项目中的详细讲解。希望本文能对您有所帮助。