Spring Boot 整合 MyBatis 連接數(shù)據(jù)庫及常見問題
MyBatis 是一個(gè)優(yōu)秀的持久層框架,支持定制化 SQL、存儲(chǔ)過程以及高級(jí)映射。下面詳細(xì)介紹如何在 Spring Boot 項(xiàng)目中整合 MyBatis 并連接數(shù)據(jù)庫。
一、基本配置
1. 添加依賴
在pom.xml
中添加以下依賴:
<!-- Spring Boot Starter Web --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- MyBatis Spring Boot Starter --> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.2.0</version> <!-- 使用最新版本 --> </dependency> <!-- 數(shù)據(jù)庫驅(qū)動(dòng),根據(jù)你的數(shù)據(jù)庫選擇 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!-- 其他可能需要的依賴 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.2.6</version> <!-- Druid 連接池 --> </dependency>
2. 配置數(shù)據(jù)庫連接
在application.yml
或application.properties
中配置數(shù)據(jù)庫連接:
# application.yml 配置示例 spring: datasource: url: jdbc:mysql://localhost:3306/your_database?useSSL=false&serverTimezone=UTC&characterEncoding=utf8 username: your_username password: your_password driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # 使用Druid連接池 # MyBatis 配置 mybatis: mapper-locations: classpath:mapper/*.xml # mapper.xml文件位置 type-aliases-package: com.example.model # 實(shí)體類所在包 configuration: map-underscore-to-camel-case: true # 開啟駝峰命名轉(zhuǎn)換
二、項(xiàng)目結(jié)構(gòu)
典型的項(xiàng)目結(jié)構(gòu)如下:
src/main/java └── com.example.demo ├── DemoApplication.java # 啟動(dòng)類 ├── config │ └── MyBatisConfig.java # MyBatis配置類(可選) ├── controller │ └── UserController.java # 控制器 ├── service │ ├── UserService.java # 服務(wù)接口 │ └── impl │ └── UserServiceImpl.java # 服務(wù)實(shí)現(xiàn) ├── mapper │ └── UserMapper.java # Mapper接口 └── model └── User.java # 實(shí)體類 src/main/resources ├── application.yml # 配置文件 └── mapper └── UserMapper.xml # SQL映射文件
三、核心組件實(shí)現(xiàn)(示例)
1. 實(shí)體類
package com.example.model; public class User { private Long id; private String username; private String password; private String email; // getters and setters // toString() }
2. Mapper 接口
package com.example.mapper; import com.example.model.User; import org.apache.ibatis.annotations.*; import java.util.List; @Mapper // 重要:標(biāo)識(shí)這是一個(gè)MyBatis的Mapper接口 public interface UserMapper { @Select("SELECT * FROM user WHERE id = #{id}") User findById(Long id); @Insert("INSERT INTO user(username, password, email) VALUES(#{username}, #{password}, #{email})") @Options(useGeneratedKeys = true, keyProperty = "id") int insert(User user); @Update("UPDATE user SET username=#{username}, password=#{password}, email=#{email} WHERE id=#{id}") int update(User user); @Delete("DELETE FROM user WHERE id=#{id}") int delete(Long id); // XML配置方式 List<User> findAll(); }
3. Mapper XML 文件
src/main/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.mapper.UserMapper"> <resultMap id="userResultMap" type="User"> <id property="id" column="id"/> <result property="username" column="username"/> <result property="password" column="password"/> <result property="email" column="email"/> </resultMap> <select id="findAll" resultMap="userResultMap"> SELECT * FROM user </select> </mapper>
4. Service 層
package com.example.service; import com.example.model.User; import java.util.List; public interface UserService { User findById(Long id); List<User> findAll(); int save(User user); int update(User user); int delete(Long id); }
service層實(shí)現(xiàn)類:
package com.example.service.impl; import com.example.mapper.UserMapper; import com.example.model.User; import com.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User findById(Long id) { return userMapper.findById(id); } @Override public List<User> findAll() { return userMapper.findAll(); } @Override public int save(User user) { return userMapper.insert(user); } @Override public int update(User user) { return userMapper.update(user); } @Override public int delete(Long id) { return userMapper.delete(id); } }
5. Controller 層:
package com.example.controller; import com.example.model.User; import com.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; import java.util.List; @RestController @RequestMapping("/users") public class UserController { @Autowired private UserService userService; @GetMapping("/{id}") public User getUser(@PathVariable Long id) { return userService.findById(id); } @GetMapping public List<User> getAllUsers() { return userService.findAll(); } @PostMapping public int createUser(@RequestBody User user) { return userService.save(user); } @PutMapping public int updateUser(@RequestBody User user) { return userService.update(user); } @DeleteMapping("/{id}") public int deleteUser(@PathVariable Long id) { return userService.delete(id); } }
四、高級(jí)特性
1. 動(dòng)態(tài)SQL
在XML中使用動(dòng)態(tài)SQL:
<select id="findByCondition" parameterType="map" resultMap="userResultMap"> SELECT * FROM user <where> <if test="username != null and username != ''"> AND username LIKE CONCAT('%', #{username}, '%') </if> <if test="email != null and email != ''"> AND email = #{email} </if> </where> </select>
2. 分頁查詢
使用PageHelper插件:
添加依賴:
<select id="findByCondition" parameterType="map" resultMap="userResultMap"> SELECT * FROM user <where> <if test="username != null and username != ''"> AND username LIKE CONCAT('%', #{username}, '%') </if> <if test="email != null and email != ''"> AND email = #{email} </if> </where> </select>
使用示例:
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper-spring-boot-starter</artifactId> <version>1.4.1</version> </dependency>
3. 多數(shù)據(jù)源配置
配置多個(gè)數(shù)據(jù)源:
spring: datasource: primary: url: jdbc:mysql://localhost:3306/db1 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver secondary: url: jdbc:mysql://localhost:3306/db2 username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver
創(chuàng)建配置類:
@Configuration @MapperScan(basePackages = "com.example.mapper.primary", sqlSessionFactoryRef = "primarySqlSessionFactory") public class PrimaryDataSourceConfig { @Bean(name = "primaryDataSource") @ConfigurationProperties(prefix = "spring.datasource.primary") public DataSource primaryDataSource() { return DataSourceBuilder.create().build(); } @Bean(name = "primarySqlSessionFactory") public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource dataSource) throws Exception { SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); bean.setDataSource(dataSource); bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/primary/*.xml")); return bean.getObject(); } @Bean(name = "primaryTransactionManager") public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } // 類似地創(chuàng)建SecondaryDataSourceConfig
五、常見問題解決
Mapper接口無法注入:
- 確保啟動(dòng)類上有
@MapperScan("com.example.mapper")
注解 - 或者每個(gè)Mapper接口上有
@Mapper
注解
XML文件找不到:
- 檢查
mybatis.mapper-locations
配置是否正確 - 確保XML文件在resources目錄下正確位置
駝峰命名不生效:
- 確認(rèn)配置
mybatis.configuration.map-underscore-to-camel-case=true
連接池配置:
- 推薦使用Druid連接池,并配置合理的連接參數(shù)
事務(wù)管理:
- 在Service方法上添加
@Transactional
注解
到此這篇關(guān)于Spring Boot 整合 MyBatis 連接數(shù)據(jù)庫及常見問題的文章就介紹到這了,更多相關(guān)Spring Boot MyBatis 連接數(shù)據(jù)庫內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot項(xiàng)目整合MybatisPlus并使用SQLite作為數(shù)據(jù)庫的過程
- Spring Boot3整合Mybatis Plus的詳細(xì)過程(數(shù)據(jù)庫為MySQL)
- SpringBoot使用MyBatis-Flex實(shí)現(xiàn)靈活的數(shù)據(jù)庫訪問
- springboot整合mybatis實(shí)現(xiàn)數(shù)據(jù)庫的更新批處理方式
- SpringBoot圖文并茂詳解如何引入mybatis與連接Mysql數(shù)據(jù)庫
- SpringBoot結(jié)合Mybatis實(shí)現(xiàn)創(chuàng)建數(shù)據(jù)庫表的方法
- Springboot Mybatis-Plus數(shù)據(jù)庫單元測(cè)試實(shí)戰(zhàn)(三種方式)
- springboot+mybatis通過實(shí)體類自動(dòng)生成數(shù)據(jù)庫表的方法
- Spring Boot整合MyBatis連接Oracle數(shù)據(jù)庫的步驟全紀(jì)錄
相關(guān)文章
Java ArrayList中存放引用數(shù)據(jù)類型的方式
這篇文章主要介紹了Java ArrayList中存放引用數(shù)據(jù)類型的方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-10-10Java遞歸運(yùn)行的機(jī)制:遞歸的微觀解讀圖文分析
這篇文章主要介紹了Java遞歸運(yùn)行的機(jī)制:遞歸的微觀解讀,結(jié)合圖文形式詳細(xì)分析了java遞歸運(yùn)行的原理、機(jī)制與相關(guān)注意事項(xiàng),需要的朋友可以參考下2020-03-03基于Java中throw和throws的區(qū)別(詳解)
下面小編就為大家?guī)硪黄贘ava中throw和throws的區(qū)別(詳解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07SpringBoot測(cè)試之@SpringBootTest與MockMvc的實(shí)戰(zhàn)應(yīng)用小結(jié)
本文將深入探討SpringBoot測(cè)試中兩個(gè)核心工具:@SpringBootTest注解與MockMvc測(cè)試框架的實(shí)戰(zhàn)應(yīng)用,幫助開發(fā)者構(gòu)建更穩(wěn)健的測(cè)試體系,提高代碼質(zhì)量與可維護(hù)性,感興趣的朋友一起看看吧2025-03-03詳解Spring Cloud Gateway基于服務(wù)發(fā)現(xiàn)的默認(rèn)路由規(guī)則
這篇文章主要介紹了詳解Spring Cloud Gateway基于服務(wù)發(fā)現(xiàn)的默認(rèn)路由規(guī)則,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-05-05Java中Comparator與Comparable排序的區(qū)別詳解
這篇文章主要介紹了Java中Comparator與Comparable排序的區(qū)別詳解,如果你有一個(gè)類,希望支持同類型的自定義比較策略,可以實(shí)現(xiàn)接口Comparable,如果某個(gè)類,沒有實(shí)現(xiàn)Comparable,但是又希望對(duì)它進(jìn)行比較,則可以自定義一個(gè)Comparator,需要的朋友可以參考下2024-01-01