Springboot2中常見的數(shù)據(jù)庫訪問方法詳解
前言
在現(xiàn)代 Java 企業(yè)級開發(fā)中,Spring Boot 已成為構(gòu)建微服務(wù)和 Web 應(yīng)用的主流框架。其“約定優(yōu)于配置”的設(shè)計理念極大地簡化了項目搭建與維護成本。而在實際開發(fā)過程中,數(shù)據(jù)庫操作 是絕大多數(shù)應(yīng)用的核心功能之一。本文將圍繞 Spring Boot 2 版本(以 2.7.x 為主),深入講解如何進行高效、穩(wěn)定的數(shù)據(jù)庫訪問,涵蓋多種主流技術(shù)棧,并結(jié)合實際案例,幫助開發(fā)者全面掌握 Spring Boot 中的數(shù)據(jù)持久化方案。
一、使用 Spring Data JPA 實現(xiàn) ORM 操作
1.1 什么是 JPA
JPA(Java Persistence API)是 Java EE 中定義的一套持久化規(guī)范,它并不直接操作數(shù)據(jù)庫,而是由具體的實現(xiàn)(如 Hibernate、EclipseLink)來完成底層工作。Spring Data JPA 是 Spring 對 JPA 規(guī)范的進一步封裝,提供了更簡潔的 API 和自動化的 CRUD 支持。
適用場景:快速開發(fā)、中小型項目、注重實體建模而非 SQL 控制的系統(tǒng)。
1.2 添加依賴并啟用 JPA
首先,在 pom.xml 文件中引入必要的依賴:
<dependencies>
<!-- Spring Data JPA 起步依賴 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL 驅(qū)動 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Web 起步依賴(用于測試接口) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Spring Boot 會自動配置以下核心組件:
EntityManagerFactory:JPA 核心工廠,負責創(chuàng)建實體管理器。PlatformTransactionManager:事務(wù)管理器,支持聲明式事務(wù)。DataSource:數(shù)據(jù)源對象。JpaRepositoriesAutoConfiguration:自動掃描并注冊 Repository 接口。
1.3 配置數(shù)據(jù)庫連接信息
在 application.yml 中配置 MySQL 數(shù)據(jù)源及 JPA 行為:
spring:
datasource:
url: jdbc:mysql://localhost:3306/springboot_db?useSSL=false&serverTimezone=UTC&characterEncoding=utf8
username: root
password: yourpassword
driver-class-name: com.mysql.cj.jdbc.Driver
jpa:
hibernate:
ddl-auto: update # 自動建表策略
show-sql: true # 控制臺輸出 SQL
properties:
hibernate:
format_sql: true # 格式化 SQL 輸出
dialect: org.hibernate.dialect.MySQL8Dialect # 指定方言
open-in-view: false # 防止 N+1 查詢問題
參數(shù)說明:
ddl-auto:
none:不做任何處理validate:驗證表結(jié)構(gòu)是否匹配update:更新表結(jié)構(gòu)(推薦開發(fā)環(huán)境)create:每次啟動都重建表(慎用)create-drop:啟動時創(chuàng)建,關(guān)閉時刪除
生產(chǎn)環(huán)境建議設(shè)置為 none,通過 Flyway 或 Liquibase 管理數(shù)據(jù)庫版本。
1.4 定義實體類(Entity)
創(chuàng)建一個用戶實體類,映射到數(shù)據(jù)庫表 user:
import javax.persistence.*;
@Entity
@Table(name = "user")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "name", length = 50, nullable = false)
private String name;
@Column(name = "age")
private Integer age;
@Column(name = "email", unique = true)
private String email;
// 構(gòu)造方法
public User() {}
public User(String name, Integer age, String email) {
this.name = name;
this.age = age;
this.email = email;
}
// Getter 和 Setter 方法省略...
}
1.5 創(chuàng)建 Repository 接口
Spring Data JPA 的強大之處在于只需定義接口,無需編寫實現(xiàn)類即可完成 CRUD 操作。
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
// 根據(jù)姓名查詢(方法名解析)
List<User> findByName(String name);
// 根據(jù)姓名和年齡查詢
List<User> findByNameAndAge(String name, Integer age);
// 模糊查詢
List<User> findByNameContaining(String keyword);
// 使用 @Query 注解自定義 SQL
@Query("SELECT u FROM User u WHERE u.age > :age")
List<User> findByAgeGreaterThan(@Param("age") Integer age);
}
方法名解析機制:Spring Data JPA 支持通過方法名自動生成查詢語句,如 findByXxxAndYyy、findByXxxOrderByYyyDesc 等。
1.6 編寫 Service 層邏輯
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
@Service
@Transactional
public class UserService {
@Autowired
private UserRepository userRepository;
public List<User> findAll() {
return userRepository.findAll();
}
public User findById(Long id) {
Optional<User> user = userRepository.findById(id);
return user.orElse(null);
}
public User save(User user) {
return userRepository.save(user);
}
public void deleteById(Long id) {
userRepository.deleteById(id);
}
public List<User> searchByName(String name) {
return userRepository.findByNameContaining(name);
}
}
1.7 控制器層暴露接口
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
public List<User> getAll() {
return userService.findAll();
}
@GetMapping("/{id}")
public User getById(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
public User create(@RequestBody User user) {
return userService.save(user);
}
@PutMapping("/{id}")
public User update(@PathVariable Long id, @RequestBody User user) {
user.setId(id);
return userService.save(user);
}
@DeleteMapping("/{id}")
public void delete(@PathVariable Long id) {
userService.deleteById(id);
}
}
1.8 測試驗證
啟動應(yīng)用后,可通過 Postman 或 curl 測試:
curl -X POST http://localhost:8080/api/users \
-H "Content-Type: application/json" \
-d '{"name":"張三","age":25,"email":"zhangsan@example.com"}'
查看控制臺輸出的 SQL 是否正常執(zhí)行。
二、集成 Druid 數(shù)據(jù)源提升性能與監(jiān)控能力
雖然 Spring Boot 默認使用 HikariCP 作為連接池,但在國內(nèi)企業(yè)級項目中,Druid 因其強大的監(jiān)控功能和穩(wěn)定性被廣泛采用。
2.1 引入 Druid 依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.11</version>
</dependency>
2.2 配置 Druid 數(shù)據(jù)源
修改 application.yml:
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
druid:
# 基礎(chǔ)連接屬性
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/springboot_db?useSSL=false&serverTimezone=UTC
username: root
password: yourpassword
# 連接池配置
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1
test-while-idle: true
test-on-borrow: false
test-on-return: false
# 打開 PSCache,并指定每個連接上 PSCache 的大小
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
# 配置監(jiān)控統(tǒng)計攔截的 filters
filters: stat,wall,log4j
# SQL 防火墻和慢 SQL 記錄
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
2.3 配置監(jiān)控頁面(StatViewServlet)
創(chuàng)建配置類啟用 Druid 監(jiān)控:
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
@Bean
@ConfigurationProperties("spring.datasource.druid")
public DataSource dataSource() {
return DruidDataSourceBuilder.create().build();
}
@Bean
public ServletRegistrationBean<StatViewServlet> statViewServlet() {
StatViewServlet servlet = new StatViewServlet();
ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(servlet, "/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "123456");
initParams.put("allow", ""); // 允許所有人訪問
initParams.put("deny", "192.168.1.1"); // 拒絕特定 IP
bean.setInitParameters(initParams);
return bean;
}
@Bean
public FilterRegistrationBean<WebStatFilter> webStatFilter() {
WebStatFilter filter = new WebStatFilter();
FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(filter);
bean.setUrlPatterns(Arrays.asList("/*"));
bean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return bean;
}
}
訪問 http://localhost:8080/druid 即可進入監(jiān)控頁面,查看:
- SQL 執(zhí)行次數(shù)、耗時
- 連接池狀態(tài)
- 慢 SQL 日志
- Web 請求統(tǒng)計
三、使用 MyBatis 進行靈活 SQL 控制
當業(yè)務(wù)邏輯復雜、需要精細控制 SQL 時,MyBatis 是更合適的選擇。
3.1 添加依賴
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.1</version>
</dependency>
3.2 配置 MyBatis
mybatis:
mapper-locations: classpath:mapping/*.xml
type-aliases-package: com.example.entity
configuration:
map-underscore-to-camel-case: true # 開啟駝峰映射
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # 控制臺打印 SQL
3.3 編寫 Mapper 接口與 XML 映射文件
接口:
@Mapper
public interface UserMapper {
List<User> findAll();
User findById(Long id);
int insert(User user);
int update(User user);
int deleteById(Long id);
}
XML 文件(src/main/resources/mapping/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="BaseResultMap" type="com.example.entity.User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<result property="email" column="email"/>
</resultMap>
<select id="findAll" resultMap="BaseResultMap">
SELECT * FROM user
</select>
<select id="findById" parameterType="long" resultMap="BaseResultMap">
SELECT * FROM user WHERE id = #{id}
</select>
<insert id="insert" parameterType="com.example.entity.User" useGeneratedKeys="true" keyProperty="id">
INSERT INTO user(name, age, email) VALUES (#{name}, #{age}, #{email})
</insert>
<update id="update" parameterType="com.example.entity.User">
UPDATE user SET name=#{name}, age=#{age}, email=#{email} WHERE id=#{id}
</update>
<delete id="deleteById" parameterType="long">
DELETE FROM user WHERE id = #{id}
</delete>
</mapper>
3.4 使用注解方式(可選)
對于簡單 SQL,可以直接使用注解:
@Mapper
public interface UserMapper {
@Select("SELECT * FROM user WHERE id = #{id}")
User findById(@Param("id") Long id);
@Insert("INSERT INTO user(name, age, email) VALUES (#{name}, #{age}, #{email})")
@Options(useGeneratedKeys = true, keyProperty = "id")
int insert(User user);
}
四、整合 MyBatis-Plus 提升開發(fā)效率
MyBatis-Plus 是 MyBatis 的增強工具,提供了通用 CRUD、分頁、代碼生成等功能,極大提升開發(fā)效率。
4.1 添加依賴
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3.1</version>
</dependency>
4.2 配置插件(分頁支持)
@Configuration
@MapperScan("com.example.mapper")
public class MyBatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 添加分頁插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
4.3 定義實體與 Mapper
@Data
@TableName("user")
public class User {
@TableId(type = IdType.AUTO)
private Long id;
private String name;
private Integer age;
private String email;
}
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
4.4 使用內(nèi)置方法完成 CRUD
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public List<User> listAll() {
return userMapper.selectList(null);
}
public IPage<User> page(int pageNum, int pageSize) {
Page<User> page = new Page<>(pageNum, pageSize);
return userMapper.selectPage(page, null);
}
public List<User> searchByName(String name) {
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.like("name", name);
return userMapper.selectList(wrapper);
}
}
4.5 條件構(gòu)造器(QueryWrapper)
QueryWrapper<User> wrapper = new QueryWrapper<>();
wrapper.gt("age", 18)
.like("name", "王")
.orderByDesc("id");
List<User> users = userMapper.selectList(wrapper);
五、其他數(shù)據(jù)庫訪問方式簡述
| 方式 | 特點 |
|---|---|
| JdbcTemplate | 輕量級,適合簡單 SQL,需手動映射結(jié)果 |
| Spring Data JDBC | 輕量 ORM,比 JPA 簡單,適合簡單對象映射 |
| R2DBC | 響應(yīng)式數(shù)據(jù)庫連接,適用于 WebFlux 架構(gòu) |
六、總結(jié)與選型建議
| 技術(shù) | 優(yōu)點 | 缺點 | 推薦場景 |
|---|---|---|---|
| JPA | 快速開發(fā),自動 CRUD | SQL 控制弱,學習曲線陡 | 中小型項目、快速原型 |
| MyBatis | SQL 靈活,易于優(yōu)化 | 需寫 XML,維護成本高 | 復雜查詢、遺留系統(tǒng) |
| MyBatis-Plus | 開發(fā)效率極高,功能豐富 | 對新手有一定門檻 | 推薦首選,尤其互聯(lián)網(wǎng)項目 |
| JdbcTemplate | 輕量、直接 | 無 ORM,編碼繁瑣 | 簡單腳本、工具類 |
| Druid | 監(jiān)控能力強,穩(wěn)定 | 配置較復雜 | 所有生產(chǎn)環(huán)境推薦集成 |
最終建議:
- 若追求開發(fā)效率與功能完整性,推薦 MyBatis-Plus + Druid
- 若團隊熟悉 JPA 且項目偏重領(lǐng)域模型,可選擇 Spring Data JPA
- 若為高并發(fā)響應(yīng)式系統(tǒng),則考慮 R2DBC
通過本文的詳細講解,相信你已經(jīng)掌握了 Spring Boot 2 中各種數(shù)據(jù)庫操作方式的核心要點。在實際項目中,合理選擇技術(shù)棧,結(jié)合業(yè)務(wù)需求,才能構(gòu)建出高性能、易維護的應(yīng)用系統(tǒng)。
以上就是Springboot2中常見的數(shù)據(jù)庫訪問方法詳解的詳細內(nèi)容,更多關(guān)于Springboot數(shù)據(jù)庫訪問的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
一文帶你搞懂java如何實現(xiàn)網(wǎng)絡(luò)NIO高并發(fā)編程
NIO是?Java?在?JDK?1.4?中引入的一套新的?I/O?API,旨在解決傳統(tǒng)?I/O高并發(fā)場景下的性能和擴展性不足的問題,下面就跟隨小編一起深入了解下NIO高并發(fā)編程吧2024-12-12
SpringCloud服務(wù)的發(fā)現(xiàn)與調(diào)用詳解
在Java微服務(wù)越來越火的今天。幾乎什么公司都在搞微服務(wù)。而使用的比較多的就是Spring?Cloud技術(shù)棧。今天就來研究一下Spring?Cloud中服務(wù)發(fā)現(xiàn)與調(diào)用的基本原理2022-07-07
IDEA的Swing可視化插件JFormDesigner詳解
JFormDesigner是一個專業(yè)的軟件應(yīng)用程序,專門用于幫助您開發(fā)Java?Swing用戶界面,而無需具備編程技能。它可作為獨立實用程序使用,也可以將其用作各種IDE的插件,本文給大家介紹idea?Swing可視化插件,感興趣的朋友一起看看吧2022-06-06
windows系統(tǒng)配置Java開發(fā)環(huán)境變量
這篇文章主要介紹了windows系統(tǒng)配置Java開發(fā)環(huán)境變量,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2021-12-12
利用Intellij Idea連接遠程服務(wù)器實現(xiàn)遠程上傳部署功能
大家在使用Intellij Idea開發(fā)程序的時候,是不是需要部署到遠程SSH服務(wù)器運行呢,當然也可以直接在idea軟件內(nèi)容實現(xiàn)配置部署操作,接下來通過本文給大家分享利用Intellij Idea連接遠程服務(wù)器實現(xiàn)遠程上傳部署功能,感興趣的朋友跟隨小編一起看看吧2021-05-05
springboot?通過博途獲取plc點位的數(shù)據(jù)代碼實現(xiàn)
這篇文章主要介紹了springboot?通過博途獲取plc點位的數(shù)據(jù)的代碼實現(xiàn),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-08-08

