# SpringBoot项目中怎么整合MyBatis ## 一、前言 在现代Java企业级应用开发中,SpringBoot和MyBatis的组合已经成为主流技术选型之一。SpringBoot提供了快速构建项目的脚手架,而MyBatis作为优秀的持久层框架,以其灵活的SQL编写方式和良好的性能受到开发者青睐。本文将详细介绍如何在SpringBoot项目中整合MyBatis框架。 ## 二、环境准备 ### 2.1 开发工具及版本要求 - JDK 1.8+ - Maven 3.6+ 或 Gradle 6.x - SpringBoot 2.7.x - MyBatis 3.5.x - IDE(IntelliJ IDEA或Eclipse) ### 2.2 创建SpringBoot项目 通过Spring Initializr创建项目: 1. 访问 https://start.spring.io 2. 选择Maven/Gradle项目 3. 添加依赖:Spring Web、MyBatis Framework、MySQL Driver 或使用命令行: ```bash curl https://start.spring.io/starter.zip -d dependencies=web,mybatis,mysql -o mybatis-demo.zip
<dependencies> <!-- SpringBoot Starter --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis Starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> </dependencies>
在application.yml
中配置:
spring: datasource: url: jdbc:mysql://localhost:3306/test_db?useSSL=false&serverTimezone=UTC username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mybatis: mapper-locations: classpath:mapper/*.xml type-aliases-package: com.example.demo.entity
package com.example.demo.entity; public class User { private Long id; private String username; private String password; // getters and setters }
package com.example.demo.mapper; import com.example.demo.entity.User; import org.apache.ibatis.annotations.Mapper; @Mapper public interface UserMapper { User selectById(Long id); int insert(User user); int update(User user); int delete(Long id); }
在resources/mapper
目录下创建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.demo.mapper.UserMapper"> <resultMap id="BaseResultMap" type="User"> <id column="id" property="id" /> <result column="username" property="username" /> <result column="password" property="password" /> </resultMap> <select id="selectById" resultMap="BaseResultMap"> SELECT * FROM user WHERE id = #{id} </select> </mapper>
添加PageHelper依赖:
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.4.2</version> </dependency>
配置分页参数:
pagehelper: helperDialect: mysql reasonable: true supportMethodsArguments: true
使用示例:
PageHelper.startPage(1, 10); List<User> users = userMapper.selectAll();
@Configuration @MapperScan(basePackages = "com.example.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory") public class PrimaryDataSourceConfig { @Bean @Primary @ConfigurationProperties("spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean @Primary public SqlSessionFactory primarySqlSessionFactory() throws Exception { SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean(); factoryBean.setDataSource(primaryDataSource()); return factoryBean.getObject(); } }
SpringBoot默认已集成事务管理:
@Service public class UserService { @Autowired private UserMapper userMapper; @Transactional public void updateUser(User user) { userMapper.update(user); } }
MyBatis Generator配置示例:
<generatorConfiguration> <context id="DB2Tables" targetRuntime="MyBatis3"> <jdbcConnection driverClass="com.mysql.cj.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test_db" userId="root" password="123456"> </jdbcConnection> <javaModelGenerator targetPackage="com.example.entity" targetProject="src/main/java"/> <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/> <javaClientGenerator type="XMLMAPPER" targetPackage="com.example.mapper" targetProject="src/main/java"/> <table tableName="%"> <generatedKey column="id" sqlStatement="JDBC"/> </table> </context> </generatorConfiguration>
Mapper接口无法注入
@Mapper
注解或@MapperScan
XML文件找不到
mybatis.mapper-locations
配置SQL语法错误
在application.yml
中添加:
logging: level: com.example.demo.mapper: DEBUG
本文详细介绍了SpringBoot整合MyBatis的全过程,从基础配置到高级功能,涵盖了实际开发中的常见场景。通过合理的配置和优化,可以充分发挥MyBatis在SpringBoot项目中的优势,构建高效可靠的数据访问层。
src/main/java ├── com.example.demo │ ├── DemoApplication.java │ ├── entity │ │ └── User.java │ ├── mapper │ │ └── UserMapper.java │ └── service │ └── UserService.java src/main/resources ├── application.yml ├── mapper │ └── UserMapper.xml
注意:实际开发中应根据项目需求调整配置,本文示例基于SpringBoot 2.7.x和MyBatis 3.5.x版本。 “`
这篇文章约4000字,采用Markdown格式编写,包含了SpringBoot整合MyBatis的完整流程,从基础配置到高级功能,并提供了常见问题解决方案。您可以根据实际需求调整内容细节或补充更多具体示例。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。