Spring Boot 整合 MyBatis 連接數(shù)據(jù)庫及常見問題
MyBatis 是一個優(yōu)秀的持久層框架,支持定制化 SQL、存儲過程以及高級映射。下面詳細介紹如何在 Spring Boot 項目中整合 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ū)動,根據(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 # 實體類所在包
configuration:
map-underscore-to-camel-case: true # 開啟駝峰命名轉(zhuǎn)換二、項目結(jié)構(gòu)
典型的項目結(jié)構(gòu)如下:
src/main/java
└── com.example.demo
├── DemoApplication.java # 啟動類
├── config
│ └── MyBatisConfig.java # MyBatis配置類(可選)
├── controller
│ └── UserController.java # 控制器
├── service
│ ├── UserService.java # 服務接口
│ └── impl
│ └── UserServiceImpl.java # 服務實現(xiàn)
├── mapper
│ └── UserMapper.java # Mapper接口
└── model
└── User.java # 實體類
src/main/resources
├── application.yml # 配置文件
└── mapper
└── UserMapper.xml # SQL映射文件三、核心組件實現(xiàn)(示例)
1. 實體類
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 // 重要:標識這是一個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層實現(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);
}
}四、高級特性
1. 動態(tài)SQL
在XML中使用動態(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ù)源配置
配置多個數(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接口無法注入:
- 確保啟動類上有
@MapperScan("com.example.mapper")注解 - 或者每個Mapper接口上有
@Mapper注解
XML文件找不到:
- 檢查
mybatis.mapper-locations配置是否正確 - 確保XML文件在resources目錄下正確位置
駝峰命名不生效:
- 確認配置
mybatis.configuration.map-underscore-to-camel-case=true
連接池配置:
- 推薦使用Druid連接池,并配置合理的連接參數(shù)
事務管理:
- 在Service方法上添加
@Transactional注解
到此這篇關(guān)于Spring Boot 整合 MyBatis 連接數(shù)據(jù)庫及常見問題的文章就介紹到這了,更多相關(guān)Spring Boot MyBatis 連接數(shù)據(jù)庫內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot項目整合MybatisPlus并使用SQLite作為數(shù)據(jù)庫的過程
- Spring Boot3整合Mybatis Plus的詳細過程(數(shù)據(jù)庫為MySQL)
- SpringBoot使用MyBatis-Flex實現(xiàn)靈活的數(shù)據(jù)庫訪問
- springboot整合mybatis實現(xiàn)數(shù)據(jù)庫的更新批處理方式
- SpringBoot圖文并茂詳解如何引入mybatis與連接Mysql數(shù)據(jù)庫
- SpringBoot結(jié)合Mybatis實現(xiàn)創(chuàng)建數(shù)據(jù)庫表的方法
- Springboot Mybatis-Plus數(shù)據(jù)庫單元測試實戰(zhàn)(三種方式)
- springboot+mybatis通過實體類自動生成數(shù)據(jù)庫表的方法
- Spring Boot整合MyBatis連接Oracle數(shù)據(jù)庫的步驟全紀錄
相關(guān)文章
Java ArrayList中存放引用數(shù)據(jù)類型的方式
這篇文章主要介紹了Java ArrayList中存放引用數(shù)據(jù)類型的方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
基于Java中throw和throws的區(qū)別(詳解)
下面小編就為大家?guī)硪黄贘ava中throw和throws的區(qū)別(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-07-07
SpringBoot測試之@SpringBootTest與MockMvc的實戰(zhàn)應用小結(jié)
本文將深入探討SpringBoot測試中兩個核心工具:@SpringBootTest注解與MockMvc測試框架的實戰(zhàn)應用,幫助開發(fā)者構(gòu)建更穩(wěn)健的測試體系,提高代碼質(zhì)量與可維護性,感興趣的朋友一起看看吧2025-03-03
詳解Spring Cloud Gateway基于服務發(fā)現(xiàn)的默認路由規(guī)則
這篇文章主要介紹了詳解Spring Cloud Gateway基于服務發(fā)現(xiàn)的默認路由規(guī)則,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-05-05
Java中Comparator與Comparable排序的區(qū)別詳解
這篇文章主要介紹了Java中Comparator與Comparable排序的區(qū)別詳解,如果你有一個類,希望支持同類型的自定義比較策略,可以實現(xiàn)接口Comparable,如果某個類,沒有實現(xiàn)Comparable,但是又希望對它進行比較,則可以自定義一個Comparator,需要的朋友可以參考下2024-01-01

