SpringBoot 项目 MyBatis 集成配置详解

在 Spring Boot 项目中使用 MyBatis,需要进行以下配置:

  1. 添加 MyBatis 和 MyBatis-Spring 的依赖到 pom.xml 文件中:
<dependencies>
    <!-- MyBatis -->
    <dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>2.2.0</version>
    </dependency>
    
    <!-- MySQL驱动 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.21</version>
    </dependency>
</dependencies>
  1. 配置数据源,可以在 application.properties 文件中添加以下配置:
spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
spring.datasource.username=root
spring.datasource.password=yourpassword
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  1. 创建 MyBatis 的配置类 MyBatisConfig.java,用于配置 MyBatis 的相关属性和扫描 Mapper 接口:
@Configuration
@MapperScan('com.example.mapper') // 指定 Mapper 接口的扫描路径
public class MyBatisConfig {
    
    @Autowired
    private DataSource dataSource;
    
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory;
    }
}
  1. 创建 Mapper 接口和对应的 XML 文件。例如,创建 UserMapper.java 接口和 UserMapper.xml 文件:
public interface UserMapper {
    User getUserById(int id);
    void addUser(User user);
    void updateUser(User user);
    void deleteUser(int id);
}
<mapper namespace='com.example.mapper.UserMapper'>
    <select id='getUserById' resultType='com.example.model.User'>
        SELECT * FROM users WHERE id = #{id}
    </select>
    
    <insert id='addUser'>
        INSERT INTO users (name, age) VALUES (#{name}, #{age})
    </insert>
    
    <update id='updateUser'>
        UPDATE users SET name = #{name}, age = #{age} WHERE id = #{id}
    </update>
    
    <delete id='deleteUser'>
        DELETE FROM users WHERE id = #{id}
    </delete>
</mapper>
  1. 在 Service 层中注入 Mapper 接口,并调用对应的方法:
@Service
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    public User getUserById(int id) {
        return userMapper.getUserById(id);
    }
    
    public void addUser(User user) {
        userMapper.addUser(user);
    }
    
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }
    
    public void deleteUser(int id) {
        userMapper.deleteUser(id);
    }
}

这样,就完成了 Spring Boot 项目中使用 MyBatis 的配置和使用。

注意:

  • 以上代码示例仅供参考,具体的配置需要根据实际情况进行调整。
  • 为了提高代码的可读性和维护性,建议使用 @MapperScan 注解来扫描 Mapper 接口,而不是在 MyBatisConfig 类中手动配置每个 Mapper 接口。
  • 为了确保代码的安全性,请勿将数据库密码直接硬编码在代码中,建议使用配置文件或环境变量来存储数据库密码。
  • 建议使用 MyBatis 的日志框架来记录 SQL 语句和执行时间,方便调试和分析问题。
  • 建议使用 MyBatis 的缓存机制来提高数据库查询效率。
  • 建议使用 MyBatis 的插件机制来扩展 MyBatis 的功能。
  • 建议使用 MyBatis 的单元测试框架来测试 MyBatis 的代码。
SpringBoot 项目 MyBatis 集成配置详解

原文地址: https://www.cveoy.top/t/topic/qnMv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录