Spring Boot + JPA 全面技术总结
版本:Spring Boot 3.x / Hibernate 6.x / Jakarta Persistence 3.x
最后更新:2026 年 7 月
适用场景:企业级应用开发、微服务架构、数据密集型系统
目录
1. 核心概念与架构
1.1 JPA vs Spring Data JPA
| 层级 | 组件 | 职责 |
|---|---|---|
| 规范层 | JPA (Jakarta Persistence API) | Java EE 标准规范,定义 ORM 接口契约 |
| 实现层 | Hibernate 6 / EclipseLink / OpenJPA | 具体实现 JPA 规范,执行 SQL 生成与对象映射 |
| 框架层 | Spring Data JPA | Spring 对 JPA 的高层封装,提供 Repository 抽象和自动查询 |
核心理念:
Spring Data JPA = 标准 JPA + Spring 集成 + 声明式查询 + 自动 CRUD1.2 核心组件协作流程
┌─────────────┐ ┌──────────────────┐ ┌─────────────────┐
│ Application │────▶│ EntityManagerFactory │────▶│ Database │
└─────────────┘ └──────────────────┘ └─────────────────┘
│ │ ▲
▼ ▼ │
┌─────────────┐ ┌──────────────────┐ │
│ Service │────▶│ EntityManager │──────────────┘
└─────────────┘ └──────────────────┘
│
▼
┌─────────────┐
│ Entity │
└─────────────┘关键组件职责:
EntityManagerFactory(线程安全,重量级):
- 应用启动时创建一次,全局共享
- 负责创建 EntityManager 实例
- 持有元数据和缓存
EntityManager(非线程安全,轻量级):
- 每个事务/会话对应一个实例
- 管理实体生命周期(persist/merge/remove/find)
- 维护一级缓存(Persistence Context)
- 支持 JPQL 和原生 SQL 查询
Persistence Context(一级缓存):
- 当前会话中所有已加载实体的集合
- 同一实体只会被加载一次(按 ID 去重)
- 事务提交前检测脏检查(dirty checking)
1.3 实体生命周期状态
┌──────────┐
│ Transient │ (瞬态:未与 EM 关联)
└─────┬────┘
│ persist()
▼
┌──────────┐
rollback() │ Managed │ (受管:EM 跟踪中)
┌────────────▶└─────────┘────────────┐
│ │ remove() │ merge()
│ ▼ │
│ ┌──────────┐ │
└─────────────│ Removed │ (已删除) │
└──────────┘ │
│
┌────────── │
│ Detached │ (游离态:脱离 EM)
└──────────┘──────────────┘状态转换规则:
- Transient → Managed:调用
persist()或merge() - Managed → Detached:事务结束、
detach()、清除上下文 - Detached → Managed:再次
merge() - 任意 → Removed:调用
remove()
2. 项目配置与初始化
2.1 Maven 依赖
<dependencies>
<!-- Spring Web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Lombok (可选) -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Testcontainers (测试用) -->
<dependency>
<groupId>org.testcontainers</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
</dependencies>2.2 application.yml 完整配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: ${DB_PASSWORD}
driver-class-name: com.mysql.cj.jdbc.Driver
# HikariCP 连接池优化
hikari:
maximum-pool-size: 20
minimum-idle: 5
connection-timeout: 30000
idle-timeout: 600000
max-lifetime: 1800000
pool-name: MyHikariPool
jpa:
# DDL 策略 (生产环境建议 validate 或 none)
hibernate:
ddl-auto: update # 开发用 update,生产用 validate
# 显示 SQL 日志
show-sql: true
properties:
hibernate:
format_sql: true
# 数据库方言 (通常自动检测,显式指定更稳定)
database-platform: org.hibernate.dialect.MySQLDialect
# 批量操作优化
open-in-view: false # 生产环境禁用 OSIV
# 二级缓存
properties:
hibernate.cache.use_second_level_cache: true
hibernate.cache.region.factory_class: org.hibernate.cache.jcache.JCacheRegionFactory
# 日志级别
logging:
level:
org.hibernate.SQL: debug
org.hibernate.type.descriptor.sql: trace # 输出参数值
org.springframework.orm.jpa: debug2.3 关键配置说明
| 配置项 | 推荐值 | 说明 |
|---|---|---|
ddl-auto | validate | 生产环境应使用 Flyway/Liquibase 管理 schema |
show-sql | true | 仅开发环境开启,生产关闭 |
open-in-view | false | 避免延迟加载在视图层触发 N+1 |
hikari.maximum-pool-size | CPU 核数 * 2 + 磁盘数 | 经验公式,需压测验证 |
3. 实体映射详解
3.1 基础实体定义
@Entity
@Table(name = "users",
indexes = {
@Index(name = "idx_email", columnList = "email", unique = true),
@Index(name = "idx_created_at", columnList = "createdAt")
},
uniqueConstraints = {
@UniqueConstraint(columnNames = {"username"})
})
public class User {
// ===== 主键 =====
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY) // 数据库自增
private Long id;
// ===== 基本字段 =====
@Column(nullable = false, length = 50, unique = true)
private String username;
@Column(nullable = false, length = 100)
private String email;
@Column(precision = 10, scale = 2)
private BigDecimal balance;
@Column(nullable = false)
private LocalDateTime createdAt;
@Column(nullable = false)
private LocalDateTime updatedAt;
// ===== 枚举映射 =====
@Enumerated(EnumType.STRING) // 强烈建议用 STRING,不要用 ORDINAL
private UserStatus status;
// ===== 审计字段 =====
@CreatedDate
private LocalDateTime createdDate;
@LastModifiedDate
private LocalDateTime lastModifiedDate;
// ===== 乐观锁 =====
@Version
private Integer version;
// ===== 构造器 =====
protected User() {} // JPA 要求无参构造
public User(String username, String email) {
this.username = username;
this.email = email;
this.createdAt = LocalDateTime.now();
this.status = UserStatus.ACTIVE;
}
// Getters and Setters...
}3.2 主键生成策略对比
| 策略 | 注解 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|---|
| IDENTITY | GenerationType.IDENTITY | 简单直接,数据库支持 | insert 后必须立即获取 ID | MySQL、PostgreSQL |
| SEQUENCE | GenerationType.SEQUENCE | 高性能,可预取 | 需要数据库支持序列 | Oracle、PostgreSQL |
| AUTO | GenerationType.AUTO | 自动选择最佳策略 | 不同数据库行为不一致 | 跨库迁移 |
| TABLE | GenerationType.TABLE | 通用性好 | 性能差,有并发问题 | 不推荐 |
| UUID | @GenericGenerator | 分布式友好,无中心依赖 | 索引效率低,存储占用大 | 微服务、分库分表 |
推荐方案:
// MySQL 推荐:自增 ID
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// 分布式系统推荐:雪花算法或 UUID
@Id
@GeneratedValue(generator = "uuid2")
@GenericGenerator(name = "uuid2", strategy = "uuid2")
private UUID id;3.3 值对象与嵌入类型
// 可嵌入的值对象
@Embeddable
public class Address {
@Column(length = 100)
private String city;
@Column(length = 200)
private String street;
@Column(length = 20)
private String zipCode;
// Constructors, getters, setters...
}
// 在实体中使用
@Entity
public class Customer {
@Embedded
private Address address;
// 其他字段...
}3.4 基类抽取 (@MappedSuperclass)
@MappedSuperclass
public abstract class BaseEntity implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Version
private Integer version;
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime updatedAt;
// Getters and Setters...
}
// 继承基类
@Entity
public class Product extends BaseEntity {
private String name;
private BigDecimal price;
// ...
}3.5 JSONB 类型映射 (Hibernate 6+)
import jakarta.persistence.Column;
import org.hibernate.type.SqlTypes;
import org.hibernate.annotations.JdbcTypeCode;
@Entity
public class Article {
@JdbcTypeCode(SqlTypes.JSON)
@Column(columnDefinition = "jsonb")
private Map<String, Object> metadata;
// 或者映射为具体 POJO
@JdbcTypeCode(SqlTypes.JSON)
@Column(columnDefinition = "jsonb")
private ArticleTags tags;
}4. Repository 接口体系
4.1 Repository 继承层次
// 最底层:纯 Spring DAO 异常翻译
interface Repository<T, ID> {
}
// 中间层:CRUD + 分页基础
interface CrudRepository<T, ID> extends Repository<T, ID> {
<S extends T> S save(S entity);
<S extends T> Iterable<S> saveAll(Iterable<S> entities);
Optional<T> findById(ID id);
boolean existsById(ID id);
Iterable<T> findAll();
Iterable<T> findAllById(Iterable<ID> ids);
long count();
void deleteById(ID id);
void delete(T entity);
void deleteAllById(Iterable<? extends ID> ids);
void deleteAll(Iterable<? extends T> entities);
void deleteAll();
}
// JPA 扩展:JPQL、Specification、flush
interface JpaRepository<T, ID> extends CrudRepository<T, ID> {
Page<T> findAll(Pageable pageable);
List<T> findAll(Specification<T> spec);
List<T> findAll(Specification<T> spec, Pageable pageable);
<S extends T> S flushAndSave(S entity);
void flush();
@Query(...) Page<T> findByXxx(...);
}
// 推荐用法
public interface UserRepository extends JpaRepository<User, Long> {
// 自定义查询方法
}4.2 自定义 Repository 实现
当声明式查询无法满足需求时,可实现自定义逻辑:
// 1. 定义接口片段
public interface UserRepositoryCustom {
Page<User> findWithRoles(String role, Pageable pageable);
}
// 2. 实现类(命名规则:接口名 + Impl)
@Repository
public class UserRepositoryImpl implements UserRepositoryCustom {
private final EntityManager entityManager;
public UserRepositoryImpl(EntityManager entityManager) {
this.entityManager = entityManager;
}
@Override
public Page<User> findWithRoles(String role, Pageable pageable) {
String jpql = "SELECT DISTINCT u FROM User u " +
"JOIN u.roles r WHERE r.name = :role";
TypedQuery<User> query = entityManager.createQuery(jpql, User.class)
.setParameter("role", role);
int total = query.getResultList().size();
query.setFirstResult((int) pageable.getOffset())
.setMaxResults(pageable.getPageSize());
List<User> content = query.getResultList();
return new PageImpl<>(content, pageable, total);
}
}
// 3. 主 Repository 继承自定义接口
public interface UserRepository extends JpaRepository<User, Long>, UserRepositoryCustom {
}4.3 REST Resource 暴露
将 Repository 直接暴露为 REST API:
@RepositoryRestResource(path = "users", collectionResourceRel = "users")
public interface UserRepository extends JpaRepository<User, Long> {
@RestResource(exported = false) // 不导出此方法
void deleteById(Long id);
}
// 生成的 REST 端点:
// GET /users
// GET /users/{id}
// POST /users
// PUT /users/{id}
// DELETE /users/{id}5. 查询方法全面指南
5.1 方法命名查询 (Query Derivation)
Spring Data JPA 可以从方法名自动生成查询:
public interface UserRepository extends JpaRepository<User, Long> {
// ===== 基础关键字 =====
List<User> findByUsername(String username); // WHERE username = ?
List<User> findByEmailContaining(String email); // WHERE email LIKE %?%
List<User> findByStatusIn(Collection<UserStatus> statuses); // WHERE status IN (?)
List<User> findByCreatedAtBetween(LocalDateTime start, LocalDateTime end);
List<User> findByBalanceGreaterThan(BigDecimal min);
// ===== 组合条件 =====
List<User> findByUsernameAndEmail(String username, String email);
List<User> findByStatusOrAgeGreaterThan(UserStatus status, int age);
List<User> findByUsernameLikeAndStatusNot(String pattern, UserStatus status);
// ===== 排序与限制 =====
List<User> findByStatusOrderByCreatedAtDesc(UserStatus status);
List<User> findByUsernameTop5(String username); // LIMIT 5
List<User> findByStatusOrderByIdAsc(UserStatus status);
// ===== 存在性判断 =====
boolean existsByEmail(String email);
long countByStatus(UserStatus status);
// ===== 删除操作 =====
@Modifying
@Transactional
void deleteByStatus(UserStatus status);
}常用关键字速查:
| 关键字 | SQL 等价 | 示例 |
|---|---|---|
And | AND | findByAAndB |
Or | OR | findByAOrB |
Not | NOT | findByANot |
Between | BETWEEN | findByABetween |
LessThan | < | findALessThan |
GreaterThan | > | findAGreaterThan |
Like | LIKE | findALike |
StartingWith | LIKE 'x%' | findAStartingWith |
EndingWith | LIKE '%x' | findAEndingWith |
Containing | LIKE '%x%' | findAContaining |
In | IN | findAIn |
NotIn | NOT IN | findANotIn |
IsNull | IS NULL | findAIsNull |
IsNotNull | IS NOT NULL | findAIsNotNull |
After | > | findAAfter |
Before | < | findABefore |
OrderBy | ORDER BY | findAOrderByB |
Top/N | LIMIT N | findATop5 |
FirstN | LIMIT N | findAFirst5 |
5.2 @Query 注解 (JPQL)
public interface OrderRepository extends JpaRepository<Order, Long> {
// 基本 JPQL
@Query("SELECT o FROM Order o WHERE o.customer.id = :customerId AND o.status = :status")
List<Order> findByCustomerAndStatus(@Param("customerId") Long customerId,
@Param("status") OrderStatus status);
// 带参数的 JPQL
@Query("SELECT u FROM User u WHERE u.email = ?1")
User findByEmailAddress(String emailAddress);
// 修改查询
@Modifying
@Transactional
@Query("UPDATE User u SET u.status = :status WHERE u.lastLoginAt < :threshold")
int deactivateInactiveUsers(@Param("status") UserStatus status,
@Param("threshold") LocalDateTime threshold);
// 删除查询
@Modifying
@Transactional
@Query("DELETE FROM Order o WHERE o.createdAt < :date")
void deleteOldOrders(@Param("date") LocalDateTime date);
}5.3 原生 SQL 查询
public interface ReportRepository extends JpaRepository<Report, Long> {
// 基本原生查询
@NativeQuery(value = "SELECT * FROM reports WHERE created_at >= ?1",
resultSetMapping = "ReportMapping")
List<Report> findRecentReports(LocalDateTime since);
// 复杂统计查询
@NativeQuery(value = """
SELECT
DATE_FORMAT(created_at, '%Y-%m') as month,
COUNT(*) as order_count,
SUM(total_amount) as revenue
FROM orders
WHERE status = 'COMPLETED'
AND created_at >= ?1
GROUP BY month
ORDER BY month DESC
""")
List<Object[]> getMonthlyRevenueStats(LocalDateTime since);
// 分页的原生查询
@NativeQuery(value = "SELECT * FROM users WHERE last_name = ?1",
countQuery = "SELECT COUNT(*) FROM users WHERE last_name = ?1")
Page<User> findByLastNamePaged(String lastName, Pageable pageable);
}5.4 Specifications 动态查询
适合复杂搜索场景,避免硬编码多个查询方法:
// 1. 构建 Specification 工厂
public class UserSpecifications {
public static Specification<User> hasNameContaining(String name) {
return (root, query, cb) ->
cb.like(root.get("name"), "%" + name + "%");
}
public static Specification<User> hasStatus(UserStatus status) {
return (root, query, cb) ->
cb.equal(root.get("status"), status);
}
public static Specification<User> createdAfter(LocalDateTime date) {
return (root, query, cb) ->
cb.greaterThan(root.get("createdAt"), date);
}
public static Specification<User> balanceBetween(BigDecimal min, BigDecimal max) {
return (root, query, cb) ->
cb.between(root.get("balance"), min, max);
}
// 组合条件
public static Specification<User> activeUserWithName(String name) {
return hasStatus(UserStatus.ACTIVE).and(hasNameContaining(name));
}
}
// 2. 在 Repository 中使用
public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
}
// 3. 在 Service 中动态构建查询
@Service
public class UserService {
private final UserRepository userRepository;
public Page<User> searchUsers(UserSearchCriteria criteria, Pageable pageable) {
Specification<User> spec = Specification.where(null);
if (criteria.getName() != null) {
spec = spec.and(UserSpecifications.hasNameContaining(criteria.getName()));
}
if (criteria.getStatus() != null) {
spec = spec.and(UserSpecifications.hasStatus(criteria.getStatus()));
}
if (criteria.getMinBalance() != null && criteria.getMaxBalance() != null) {
spec = spec.and(UserSpecifications.balanceBetween(
criteria.getMinBalance(),
criteria.getMaxBalance()
));
}
return userRepository.findAll(spec, pageable);
}
}5.5 Projections (DTO 投影)
减少数据传输量,提升性能:
// 1. 接口投影 (Interface-based Projection)
public interface UserSummary {
Long getId();
String getUsername();
String getEmail();
UserStatus getStatus();
}
public interface UserRepository extends JpaRepository<User, Long> {
List<UserSummary> findByStatus(UserStatus status);
}
// 2. 类投影 (Class-based Projection)
public class UserDto {
private final Long id;
private final String username;
private final String email;
// 必须有全参构造器
public UserDto(Long id, String username, String email) {
this.id = id;
this.username = username;
this.email = email;
}
}
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT new com.example.dto.UserDto(u.id, u.username, u.email) FROM User u")
List<UserDto> findAllAsDto();
}
// 3. Record 投影 (Java 16+)
record UserRecord(Long id, String username, String email) {}
public interface UserRepository extends JpaRepository<User, Long> {
@Query("SELECT u FROM User u WHERE u.status = :status")
List<UserRecord> findByStatusAsRecord(@Param("status") UserStatus status);
}5.6 Entity Graphs (实体图)
控制关联加载策略,解决 N+1 问题:
// 1. 定义命名实体图
@Entity
@NamedEntityGraphs({
@NamedEntityGraph(
name = "User.withRoles",
attributeNodes = @NamedAttributeNode("roles"),
subAttributeNodes = @Subgraph(
attributeName = "roles",
attributeNodes = @NamedAttributeNode("permissions")
)
),
@NamedEntityGraph(
name = "User.withAddress",
attributeNodes = @NamedAttributeNode("address")
)
})
public class User {
@ManyToMany(fetch = FetchType.LAZY)
private Set<Role> roles;
@Embedded
private Address address;
}
// 2. 在 Repository 方法上引用
public interface UserRepository extends JpaRepository<User, Long> {
// 引用命名实体图
@EntityGraph("User.withRoles")
User findByIdWithRoles(Long id);
// 临时实体图
@EntityGraph(attributePaths = {"address"})
List<User> findAllWithAddress();
// 混合使用
@EntityGraph(value = "User.withRoles", type = EntityGraphType.FETCH)
List<User> findActiveUsers();
}6. 事务管理
6.1 事务传播行为
| 传播行为 | 说明 | 典型场景 |
|---|---|---|
| REQUIRED | 如果当前存在事务则加入,否则新建 | 默认行为,大多数业务方法 |
| SUPPORTS | 如果当前存在事务则加入,否则非事务执行 | 查询方法,不需要强一致性 |
| MANDATORY | 必须在已有事务中运行,否则抛异常 | 强制要求调用方开启事务 |
| REQUIRES_NEW | 总是新建事务,挂起当前事务 | 日志记录、独立业务流程 |
| NOT_SUPPORTED | 非事务执行,挂起当前事务 | 性能敏感的读操作 |
| NEVER | 必须非事务执行,否则抛异常 | 明确禁止事务的场景 |
| NESTED | 嵌套事务,支持保存点 | 部分回滚场景 |
6.2 事务隔离级别
@Transactional(isolation = Isolation.READ_COMMITTED) // 默认级别
public void transferMoney(Account from, Account to, BigDecimal amount) {
from.debit(amount);
to.credit(amount);
}| 隔离级别 | 脏读 | 不可重复读 | 幻读 | 性能 | 适用场景 |
|---|---|---|---|---|---|
| READ_UNCOMMITTED | ✅ | ✅ | ✅ | 最高 | 几乎不用 |
| READ_COMMITTED | ❌ | ✅ | ✅ | 高 | PostgreSQL 默认 |
| REPEATABLE_READ | ❌ | ❌ | ✅ | 中 | MySQL 默认 |
| SERIALIZABLE | ❌ | ❌ | ❌ | 最低 | 金融级一致性 |
6.3 正确的事务边界设计
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final InventoryService inventoryService;
private final PaymentService paymentService;
/**
* 创建订单 - 整个流程应在一个事务中
*/
@Transactional
public Order createOrder(OrderRequest request) {
// 1. 检查库存
inventoryService.checkAvailability(request.getItems());
// 2. 扣减库存
inventoryService.decreaseStock(request.getItems());
// 3. 创建订单
Order order = new Order(request);
orderRepository.save(order);
// 4. 发起支付 (外部调用应在事务外或使用可靠消息)
// ⚠️ 不要在长事务中调用远程服务
return order;
}
/**
* 取消订单 - 需要补偿机制
*/
@Transactional
public void cancelOrder(Long orderId) {
Order order = orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException(orderId));
if (order.getStatus() == OrderStatus.COMPLETED) {
throw new IllegalStateException("Cannot cancel completed order");
}
// 恢复库存
inventoryService.increaseStock(order.getItems());
// 更新订单状态
order.setStatus(OrderStatus.CANCELLED);
orderRepository.save(order);
}
/**
* 只读查询 - 优化性能
*/
@Transactional(readOnly = true)
public List<Order> getUserOrders(Long userId) {
return orderRepository.findByUserId(userId);
}
}6.4 事务失效的三大陷阱
// ❌ 陷阱 1: 方法不是 public
@Transactional
private void savePrivate() { ... } // 事务不生效!
// ✅ 修正
@Transactional
public void savePublic() { ... }
// ❌ 陷阱 2: 同类内部调用 (绕过代理)
@Service
public class UserService {
public void createUser(User user) {
this.saveUser(user); // ❌ 不走代理,事务失效
}
@Transactional
public void saveUser(User user) {
userRepository.save(user);
}
}
// ✅ 修正方案 1: 注入自身代理
@Service
public class UserService {
@Autowired
private UserService self; // Spring 会注入代理对象
public void createUser(User user) {
self.saveUser(user); // ✅ 通过代理调用
}
@Transactional
public void saveUser(User user) {
userRepository.save(user);
}
}
// ✅ 修正方案 2: 拆分为两个 Bean
@Service
public class UserService {
@Autowired
private UserPersistenceService persistenceService;
public void createUser(User user) {
persistenceService.saveUser(user); // ✅ 跨 Bean 调用
}
}
@Service
public class UserPersistenceService {
@Transactional
public void saveUser(User user) {
userRepository.save(user);
}
}
// ❌ 陷阱 3: 异常被吞掉
@Transactional
public void process() {
try {
riskyOperation();
} catch (Exception e) {
log.error("Failed", e);
// ❌ 异常被捕获,事务不会回滚
}
}
// ✅ 修正
@Transactional(rollbackFor = Exception.class) // 明确指定回滚异常
public void process() {
try {
riskyOperation();
} catch (Exception e) {
log.error("Failed", e);
throw new BusinessException("Processing failed", e); // ✅ 重新抛出
}
}7. 关联关系与级联操作
7.1 四种基本关系
一对一 (@OneToOne)
@Entity
public class User {
@Id
@GeneratedValue
private Long id;
// 单向一对多
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "profile_id")
private UserProfile profile;
}
@Entity
public class UserProfile {
@Id
@GeneratedValue
private Long id;
private String bio;
private String avatarUrl;
}一对多 (@OneToMany)
@Entity
public class Company {
@Id
@GeneratedValue
private Long id;
private String name;
// 正向一对多 (拥有方)
@OneToMany(mappedBy = "company", cascade = CascadeType.ALL, orphanRemoval = true)
private List<Employee> employees = new ArrayList<>();
// 添加员工的方法
public void addEmployee(Employee employee) {
employees.add(employee);
employee.setCompany(this); // 维护双向关系
}
public void removeEmployee(Employee employee) {
employees.remove(employee);
employee.setCompany(null);
}
}
@Entity
public class Employee {
@Id
@GeneratedValue
private Long id;
private String name;
// 反向多对一
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "company_id")
private Company company;
}多对多 (@ManyToMany)
@Entity
public class Student {
@Id
@GeneratedValue
private Long id;
private String name;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(
name = "student_course",
joinColumns = @JoinColumn(name = "student_id"),
inverseJoinColumns = @JoinColumn(name = "course_id")
)
private Set<Course> courses = new HashSet<>();
}
@Entity
public class Course {
@Id
@GeneratedValue
private Long id;
private String title;
@ManyToMany(mappedBy = "courses")
private Set<Student> students = new HashSet<>();
}⚠️ 重要提醒: @ManyToMany 的连接表只能包含双方主键,无法添加额外字段。如果需要存储成绩、选课时间等,应改用中间实体:
// 中间实体方案
@Entity
public class StudentCourseEnrollment {
@Id
@GeneratedValue
private Long id;
@ManyToOne
@JoinColumn(name = "student_id")
private Student student;
@ManyToOne
@JoinColumn(name = "course_id")
private Course course;
private BigDecimal score;
private LocalDateTime enrolledAt;
}7.2 级联操作详解
| 级联类型 | 说明 | 使用场景 |
|---|---|---|
| PERSIST | 父实体 persist 时,子实体也 persist | 新增时级联保存 |
| MERGE | 父实体 merge 时,子实体也 merge | 更新时级联合并 |
| REMOVE | 父实体 remove 时,子实体也 remove | 删除时级联删除 |
| REFRESH | 父实体 refresh 时,子实体也 refresh | 刷新时级联重载 |
| DETACH | 父实体 detach 时,子实体也 detach | 分离时级联解绑 |
| ALL | 以上全部 | 完全生命周期管理 |
⚠️ 级联操作的陷阱:
// ❌ 危险: CascadeType.ALL 可能导致意外删除
@Entity
public class Order {
@OneToMany(mappedBy = "order", cascade = CascadeType.ALL)
private List<OrderItem> items;
}
// 当执行 orderRepository.delete(order) 时:
// 1. 先删除所有 OrderItem
// 2. 再删除 Order
// 如果 OrderItem 被其他地方引用,可能产生孤儿记录
// ✅ 安全做法: 明确指定需要的级联
@OneToMany(mappedBy = "order", cascade = {CascadeType.PERSIST, CascadeType.MERGE}, orphanRemoval = true)
private List<OrderItem> items;7.3 抓取策略 (Fetch Type)
// 立即加载 (EAGER)
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "customer_id")
private Customer customer;
// 延迟加载 (LAZY) - 推荐默认值
@OneToMany(mappedBy = "order", fetch = FetchType.LAZY)
private List<OrderItem> items;选择原则:
- @ManyToOne: 通常 EAGER (关联对象体积小,经常访问)
- @OneToMany: 通常 LAZY (集合可能很大,按需加载)
- @OneToOne: 视情况而定,双向关系建议 LAZY
- @ManyToMany: 必须 LAZY (容易引发笛卡尔积爆炸)
7.4 双向关系维护
// ❌ 错误: 只维护一方
public void assignEmployeeToCompany(Employee emp, Company company) {
emp.setCompany(company);
// 忘记 company.getEmployees().add(emp)
// 结果: 数据库中 company_id 为空
}
// ✅ 正确: 同时维护双方
public void assignEmployeeToCompany(Employee emp, Company company) {
emp.setCompany(company);
company.getEmployees().add(emp);
}
// ✅ 更好: 封装在领域方法中
@Entity
public class Company {
public void hire(Employee employee) {
this.employees.add(employee);
employee.setCompany(this);
}
public void fire(Employee employee) {
this.employees.remove(employee);
employee.setCompany(null);
}
}8. 性能优化
8.1 N+1 查询问题及解决方案
问题复现:
// ❌ 触发 N+1
List<Order> orders = orderRepository.findAll(); // 1 次查询
for (Order order : orders) {
System.out.println(order.getCustomer().getName()); // N 次查询
}
// 总计: 1 + N 次 SQL解决方案矩阵:
方案 1: JOIN FETCH (JPQL)
// ✅ 推荐用于固定关联场景
@Query("SELECT o FROM Order o JOIN FETCH o.customer")
List<Order> findAllWithCustomer();
// 多个关联
@Query("SELECT o FROM Order o " +
"JOIN FETCH o.customer c " +
"JOIN FETCH c.address")
List<Order> findAllWithCustomerAndAddress();
// 注意: JOIN FETCH 不能与分页一起使用 (会导致内存分页)
// Page<Order> findAllWithCustomer(Pageable pageable); // ❌ 无效方案 2: Entity Graph
// ✅ 灵活可控,适合动态场景
@EntityGraph(attributePaths = {"customer", "items"})
List<Order> findAllWithRelations();
// 结合 Specification
@EntityGraph(attributePaths = {"customer"})
Page<Order> findAll(Specification<Order> spec, Pageable pageable);方案 3: Batch Fetching
// ✅ 适合大量独立实体,避免笛卡尔积
@Entity
public class Order {
@BatchSize(size = 50) // 每 50 个实体一批加载
@OneToMany(mappedBy = "order")
private List<OrderItem> items;
}
// 效果: 原来 N 次单条查询 → 1 次 IN 查询 (最多 50 个 ID)方案 4: DTO 投影
// ✅ 最优解:只查需要的字段
record OrderSummary(Long orderId, String customerName, BigDecimal total) {}
@Query("""
SELECT new com.example.dto.OrderSummary(o.id, c.name, o.total)
FROM Order o JOIN o.customer c
""")
List<OrderSummary> findOrderSummaries();8.2 批量操作优化
// ❌ 低效: 逐条插入
for (User user : users) {
userRepository.save(user); // 每次 flush 一次
}
// ✅ 高效: 批量保存 + 定期 flush
@Transactional
public void bulkInsert(List<User> users) {
for (int i = 0; i < users.size(); i++) {
userRepository.save(users.get(i));
// 每 50 条 flush 一次,清空持久化上下文
if (i % 50 == 0) {
entityManager.flush();
entityManager.clear();
}
}
entityManager.flush();
}
// 配置 batch size (application.yml)
spring:
jpa:
properties:
hibernate:
jdbc:
batch_size: 50
order_inserts: true
order_updates: trueHibernate 批量配置:
spring:
jpa:
properties:
hibernate:
jdbc:
batch_size: 50 # 批量大小
order_inserts: true # 按实体类型排序 INSERT
order_updates: true # 按实体类型排序 UPDATE
use_get_before_put: true # PUT 前先 GET8.3 分页优化
// ❌ 问题: 高偏移量分页慢
// SELECT * FROM orders ORDER BY created_at DESC LIMIT 10 OFFSET 10000
// MySQL 需要扫描前 10000 条记录
// ✅ 方案 1: 游标分页 (Keyset Pagination)
public interface OrderRepository extends JpaRepository<Order, Long> {
@Query("""
SELECT o FROM Order o
WHERE o.createdAt < :cursor
ORDER BY o.createdAt DESC
""")
List<Order> findBeforeCursor(@Param("cursor") LocalDateTime cursor, Pageable pageable);
}
@Service
public class OrderService {
public CursorPage<Order> getOrders(CursorRequest request) {
LocalDateTime cursor = request.getLastSeenCreatedAt();
List<Order> orders = orderRepository.findBeforeCursor(cursor,
PageRequest.of(0, request.getSize()));
return new CursorPage<>(orders,
orders.isEmpty() ? null : orders.get(orders.size()-1).getCreatedAt());
}
}
// ✅ 方案 2: 禁用 COUNT 查询
// 如果前端不需要总页数,可以用 Slice 代替 Page
Slice<Order> findByStatus(OrderStatus status, Pageable pageable); // 不执行 COUNT
// ✅ 方案 3: 覆盖索引
@Table(indexes = {
@Index(name = "idx_status_created", columnList = "status, created_at DESC")
})
@Entity
public class Order {
// ...
}8.4 连接池调优
spring:
datasource:
hikari:
# 经验公式: connections = ((core_count * 2) + effective_spindle_count)
maximum-pool-size: 20
minimum-idle: 5
# 超时设置
connection-timeout: 30000 # 获取连接等待时间
validation-timeout: 5000 # 连接验证超时
idle-timeout: 600000 # 空闲连接存活时间 (10分钟)
max-lifetime: 1800000 # 连接最大存活时间 (30分钟)
# 连接泄漏检测
leak-detection-threshold: 60000 # 超过 60 秒未释放告警8.5 二级缓存
spring:
jpa:
properties:
hibernate:
cache:
use_second_level_cache: true
region:
factory_class: org.hibernate.cache.jcache.JCacheRegionFactory
# 需要引入 JCache 实现 (如 Ehcache3)
dependencies:
- org.ehcache:ehcache:3.10.8实体级缓存注解:
@Entity
@Cacheable
@org.hibernate.annotations.Cache(usage = CacheConcurrencyStrategy.READ_WRITE)
public class ReferenceData {
// 适合低频变更的参考数据
}⚠️ 注意: 二级缓存适用于读多写少的场景,频繁更新的实体不适合启用。
9. 高级特性
9.1 审计功能
// 1. 启用审计
@Configuration
@EnableJpaAuditing
public class JpaConfig {
// 可选: 自定义审计值提供者
@Bean
public AuditorAware<String> auditorProvider() {
return () -> Optional.of(CurrentUserContext.getUsername());
}
}
// 2. 在实体中标记审计字段
@Entity
public class Article {
@CreatedDate
private LocalDateTime createdAt;
@CreatedBy
private String createdBy;
@LastModifiedDate
private LocalDateTime updatedAt;
@LastModifiedBy
private String updatedBy;
}9.2 乐观锁与悲观锁
乐观锁 (@Version)
@Entity
public class Product {
@Id
@GeneratedValue
private Long id;
private String name;
private BigDecimal price;
@Version
private Integer version; // 每次更新自动递增
}
// 并发更新示例
@Transactional
public void updatePrice(Long productId, BigDecimal newPrice) {
Product product = productRepository.findById(productId)
.orElseThrow();
product.setPrice(newPrice);
productRepository.save(product); // 自动 WHERE version = ?
// 如果另一个事务已修改该记录,抛出 OptimisticLockException
}悲观锁 (FOR UPDATE)
// 方式 1: JPQL
@Lock(LockModeType.PESSIMISTIC_WRITE)
@Query("SELECT p FROM Product p WHERE p.id = :id")
Optional<Product> findByIdForUpdate(@Param("id") Long id);
// 方式 2: EntityManager
@Transactional
public void deductStock(Long productId, int quantity) {
Product product = entityManager.find(Product.class, productId, LockModeType.PESSIMISTIC_WRITE);
if (product.getStock() < quantity) {
throw new InsufficientStockException();
}
product.setStock(product.getStock() - quantity);
entityManager.merge(product);
}选择原则:
- 乐观锁: 冲突率低 (< 1%),读多写少
- 悲观锁: 冲突率高,写操作密集,需要强一致性
9.3 监听器与回调
// 实体监听器
@EntityListeners(AuditingEntityListener.class)
@Entity
public class Order {
@PrePersist
public void prePersist() {
this.createdAt = LocalDateTime.now();
this.orderNumber = generateOrderNumber();
}
@PreUpdate
public void preUpdate() {
this.updatedAt = LocalDateTime.now();
}
@PostLoad
public void postLoad() {
// 实体从数据库加载后执行
// 可用于计算派生字段
}
@PreRemove
public void preRemove() {
// 删除前清理资源
notifyCancellation();
}
}9.4 多租户支持
// 方案 1: 行级隔离 (Discriminator)
@Entity
public class TenantEntity {
@Column(name = "tenant_id", nullable = false)
private String tenantId;
}
// 自定义 Filter
@Component
public class TenantFilter {
@PostConstruct
public void init() {
Session session = entityManager.unwrap(Session.class);
Filter filter = session.enableFilter("TenantFilter");
filter.setParameter("tenantId", CurrentTenant.get());
}
}
// 在实体上启用过滤
@Entity
@SqlResultSetMapping(...)
public class Customer {
@Where(clause = "tenant_id = :tenantId") // Hibernate 特定
// 或使用 JPA Filter
@FilterDef(name = "tenantFilter", parameters = @ParamDef(name = "tenantId"))
@Filter(name = "tenantFilter", condition = "tenant_id = :tenantId")
private String tenantId;
}9.5 事件驱动
// 发布领域事件
@Component
public class OrderEventListener {
@EventListener
@Async // 异步处理
public void onOrderCreated(OrderCreatedEvent event) {
// 发送通知、更新缓存等
notificationService.sendOrderConfirmation(event.getOrderId());
}
}
// 在 Service 中发布事件
@Service
public class OrderService {
@Autowired
private ApplicationEventPublisher eventPublisher;
@Transactional
public Order createOrder(OrderRequest request) {
Order order = new Order(request);
orderRepository.save(order);
// 发布事件 (事务提交后触发)
eventPublisher.publishEvent(new OrderCreatedEvent(order.getId()));
return order;
}
}10. 常见陷阱与解决方案
10.1 懒加载异常 (LazyInitializationException)
// ❌ 问题: 在事务外访问懒加载属性
@GetMapping("/orders/{id}")
public OrderDto getOrder(@PathVariable Long id) {
Order order = orderRepository.findById(id).orElseThrow();
return new OrderDto(order.getItems().size()); // ❌ LazyInitializationException
}
// ✅ 解决方案 1: 使用 @Transactional
@GetMapping("/orders/{id}")
@Transactional(readOnly = true)
public OrderDto getOrder(@PathVariable Long id) {
Order order = orderRepository.findById(id).orElseThrow();
return new OrderDto(order.getItems().size()); // ✅ 在事务内
}
// ✅ 解决方案 2: JOIN FETCH
@Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.id = :id")
Optional<Order> findByIdWithItems(@Param("id") Long id);
// ✅ 解决方案 3: DTO 投影
@Query("""
SELECT new com.example.dto.OrderDto(o.id, SIZE(o.items))
FROM Order o WHERE o.id = :id
""")
Optional<OrderDto> findByIdAsDto(@Param("id") Long id);10.2 save() 的 INSERT vs UPDATE 语义
// save() 的行为取决于 ID 是否为 null
public User save(User user) {
if (user.getId() == null) {
em.persist(user); // INSERT
} else {
em.merge(user); // UPDATE
}
return user;
}
// ⚠️ 陷阱: merge 返回的是托管实例,不是传入的对象
User managed = repository.save(detachedUser);
managed.setName("New Name"); // ✅ 修改托管实例
// detachedUser.setName("New Name"); // ❌ 修改游离实例,不会被持久化
// ✅ 最佳实践: 始终使用返回值
User saved = repository.save(user);
saved.setAdditionalField(value);
repository.save(saved);10.3 循环引用导致栈溢出
// ❌ 危险: 双向关系 + Jackson 序列化
@Entity
public class A {
@OneToOne
private B b;
}
@Entity
public class B {
@OneToOne
private A a;
}
// Controller 返回实体时,Jackson 无限递归
@GetMapping
public A getA() {
return aRepository.findById(1L).orElseThrow(); // ❌ StackOverflowError
}
// ✅ 解决方案 1: @JsonIgnore
@Entity
public class B {
@OneToOne
@JsonIgnore // 忽略反向引用
private A a;
}
// ✅ 解决方案 2: DTO 投影 (推荐)
record ADto(Long id, String name, BDto nested) {}
record BDto(Long id, String name) {} // 不包含反向引用
// ✅ 解决方案 3: @JsonManagedReference / @JsonBackReference
@Entity
public class A {
@OneToOne
@JsonManagedReference
private B b;
}
@Entity
public class B {
@OneToOne
@JsonBackReference
private A a;
}10.4 事务中的远程调用
// ❌ 危险: 长事务持有数据库连接
@Transactional
public void placeOrder(OrderRequest request) {
Order order = createOrder(request);
// 远程调用可能耗时几秒到几十秒
paymentGateway.charge(order.getTotal()); // ❌ 长时间占用 DB 连接
order.markAsPaid();
orderRepository.save(order);
}
// ✅ 正确: 缩小事务边界
public void placeOrder(OrderRequest request) {
Order order = createOrderInTx(request); // 短事务
// 事务外调用远程服务
paymentGateway.charge(order.getTotal());
markAsPaidInTx(order.getId()); // 新短事务
}
@Transactional
private Order createOrderInTx(OrderRequest request) {
Order order = new Order(request);
return orderRepository.save(order);
}
@Transactional
private void markAsPaidInTx(Long orderId) {
Order order = orderRepository.findById(orderId).orElseThrow();
order.markAsPaid();
orderRepository.save(order);
}10.5 分页与 JOIN FETCH 冲突
// ❌ 错误: JOIN FETCH + 分页会导致内存分页
@Query("SELECT o FROM Order o JOIN FETCH o.customer")
Page<Order> findAllWithCustomer(Pageable pageable); // 实际执行两次查询,第二次忽略 FETCH
// ✅ 方案 1: 两阶段查询
public Page<Order> findAllWithCustomerOptimized(Pageable pageable) {
// 第一阶段: 分页查询 ID
Page<Long> idPage = orderRepository.findIds(pageable);
// 第二阶段: 根据 ID 批量加载完整实体
List<Order> orders = orderRepository.findAllByIdWithFetch(idPage.getContent());
return new PageImpl<>(orders, pageable, idPage.getTotalElements());
}
// ✅ 方案 2: 使用 Entity Graph + 手动计数
@EntityGraph(attributePaths = {"customer"})
List<Order> findAllWithCustomer(Sort sort, Pageable pageable);
long countByStatus(OrderStatus status);
// Service 层组装
public Page<Order> getPagedOrders(Pageable pageable) {
List<Order> content = orderRepository.findAllWithCustomer(null, pageable);
long total = orderRepository.count();
return new PageImpl<>(content, pageable, total);
}10.6 枚举映射陷阱
// ❌ 危险: ORDINAL 存储
@Enumerated(EnumType.ORDINAL)
private UserStatus status; // 数据库中存 0, 1, 2
// 如果调整枚举顺序:
public enum UserStatus {
ACTIVE, // 原 0
PENDING, // 原 1 → 变成 0
SUSPENDED // 原 2 → 变成 1
}
// 结果: 所有数据的状态都错了!
// ✅ 正确: 使用 STRING
@Enumerated(EnumType.STRING)
private UserStatus status; // 数据库中存 "ACTIVE", "PENDING"
// ✅ 更灵活: 自定义 Converter
@Converter(autoApply = true)
public class UserStatusConverter implements AttributeConverter<UserStatus, String> {
@Override
public String convertToDatabaseColumn(UserStatus attribute) {
return attribute != null ? attribute.getCode() : null;
}
@Override
public UserStatus convertToEntityAttribute(String dbData) {
return dbData != null ? UserStatus.fromCode(dbData) : null;
}
}11. 最佳实践清单
11.1 实体设计
- [ ] 使用
@Entity标记实体类 - [ ] 提供无参构造函数
- [ ] 金额使用
BigDecimal,时间使用LocalDateTime - [ ] 枚举使用
@Enumerated(EnumType.STRING) - [ ] 合理使用
@Table定义索引和唯一约束 - [ ] 公共字段抽取到
@MappedSuperclass - [ ] 值对象使用
@Embeddable - [ ] 避免在实体中使用基本类型包装类的可变对象
11.2 关联关系
- [ ]
@ManyToOne默认 EAGER,@OneToMany默认 LAZY - [ ] 双向关系必须同时维护两端
- [ ] 谨慎使用
CascadeType.ALL,明确指定所需级联 - [ ] 考虑使用
orphanRemoval = true自动删除孤儿记录 - [ ] 多对多优先使用中间实体而非
@JoinTable
11.3 查询优化
- [ ] 避免 N+1 查询,使用 JOIN FETCH 或 Entity Graph
- [ ] 大数据量分页使用游标分页
- [ ] 只查需要的字段,使用 DTO 投影
- [ ] 复杂动态查询使用 Specification
- [ ] 高频查询建立合适的索引
- [ ] 批量操作定期 flush 和 clear
11.4 事务管理
- [ ] 事务边界尽量小,避免长事务
- [ ] 只在 Service 层标注
@Transactional - [ ] 只读查询使用
readOnly = true - [ ] 不在事务中调用远程服务
- [ ] 正确处理异常,必要时指定
rollbackFor - [ ] 同类内部调用通过代理或拆分 Bean
11.5 生产环境配置
- [ ]
ddl-auto设置为validate或none - [ ] 使用 Flyway/Liquibase 管理 schema 变更
- [ ] 关闭
show-sql - [ ] 禁用
open-in-view - [ ] 合理配置连接池大小
- [ ] 启用慢查询日志
- [ ] 配置健康检查和监控指标
11.6 测试策略
- [ ] 单元测试使用
@DataJpaTest - [ ] 集成测试使用 Testcontainers
- [ ] 避免在测试中依赖 H2 的特殊行为
- [ ] 测试事务回滚的正确性
- [ ] 测试并发场景下的乐观锁行为
12. 调试与监控
12.1 SQL 日志配置
# 开发环境完整 SQL 日志
logging:
level:
org.hibernate.SQL: debug
org.hibernate.type.descriptor.sql: trace # 输出参数值
org.springframework.orm.jpa.JpaTransactionManager: debug
spring:
jpa:
show-sql: true
properties:
hibernate:
format_sql: true示例输出:
2026-07-17 10:30:45 DEBUG [main] org.hibernate.SQL:
select
u1_0.id,
u1_0.created_at,
u1_0.email,
u1_0.status,
u1_0.username
from
users u1_0
where
u1_0.status=?
2026-07-17 10:30:45 TRACE [main] org.hibernate.type.descriptor.sql.BasicBinder:
binding parameter [1] as [VARCHAR] - ACTIVE12.2 Hibernate Statistics
@Component
public class JpaStatisticsMonitor {
private final EntityManagerFactory emf;
public JpaStatisticsMonitor(EntityManagerFactory emf) {
this.emf = emf;
}
@Scheduled(fixedRate = 60000) // 每分钟打印一次
public void printStats() {
Statistics stats = emf.unwrap(SessionFactory.class).getStatistics();
if (stats.isStatisticsEnabled()) {
log.info("=== JPA Statistics ===");
log.info("Query executions: {}", stats.getQueryExecutionCount());
log.info("Cache hit ratio: {:.2%}", stats.getSecondLevelCacheHitRatio());
log.info("Flush count: {}", stats.getFlushCount());
log.info("Entity inserts: {}", stats.getEntityInsertCount());
log.info("Entity updates: {}", stats.getEntityUpdateCount());
log.info("Entity deletes: {}", stats.getEntityDeleteCount());
// 最慢的 10 个查询
stats.getQueryPlanEntries().entrySet().stream()
.sorted(Map.Entry.<String, QueryPlan>comparingLong(e -> e.getValue().getExecutions()))
.limit(10)
.forEach(entry ->
log.warn("Slow query: {} (executed {} times)",
entry.getKey(), entry.getValue().getExecutions())
);
}
}
}启用统计:
spring:
jpa:
properties:
hibernate:
generate_statistics: true12.3 P6Spy SQL 监控
<!-- pom.xml -->
<dependency>
<groupId>p6spy</groupId>
<artifactId>spy</artifactId>
<version>3.9.4</version>
</dependency># spy.properties
driverlist=com.p6spy.engine.spy.P6SpyDriver
logMessageFormat=com.p6spy.engine.logging.P6LogFactory
appender=com.p6spy.engine.spy.appender.Slf4JLogger
executionThreshold=500 # 超过 500ms 的记录# application.yml
spring:
datasource:
driver-class-name: com.p6spy.engine.spy.P6SpyDriver
url: jdbc:p6spy:mysql://localhost:3306/mydb12.4 Actuator 健康检查
management:
endpoints:
web:
exposure:
include: health,metrics,prometheus
endpoint:
health:
show-details: always
health:
db:
enabled: true
diskspace:
enabled: true自定义健康指示器:
@Component
public class JpaHealthIndicator implements HealthIndicator {
private final EntityManager entityManager;
@Override
public Health health() {
try {
// 执行简单查询验证连接
Long count = entityManager.createNativeQuery("SELECT COUNT(*) FROM users")
.getSingleResult();
return Health.up()
.withDetail("userCount", count)
.build();
} catch (Exception e) {
return Health.down(e).build();
}
}
}12.5 Prometheus 指标
// 自定义 JPA 查询耗时指标
@Component
public class JpaMetricsCollector {
private final MeterRegistry meterRegistry;
@Aspect
@Around("@annotation(org.springframework.data.repository.query.Query)")
public Object measureQueryTime(ProceedingJoinPoint joinPoint) throws Throwable {
Timer.Sample sample = Timer.start(meterRegistry);
try {
return joinPoint.proceed();
} finally {
sample.stop(Timer.builder("jpa.query.time")
.tag("method", joinPoint.getSignature().getName())
.register(meterRegistry));
}
}
}附录
A. 常用配置速查表
| 配置项 | 开发环境 | 生产环境 |
|---|---|---|
ddl-auto | update | validate |
show-sql | true | false |
open-in-view | true | false |
generate_statistics | true | false |
hikari.maximum-pool-size | 10 | 20-50 |
B. 常见问题 FAQ
Q1: 为什么我的查询没有走索引? A: 检查是否使用了函数包裹列 (WHERE YEAR(created_at) = 2024),这会阻止索引使用。改为范围查询: WHERE created_at >= '2024-01-01' AND created_at < '2025-01-01'。
Q2: 如何避免内存溢出? A:
- 永远不要一次性加载全表数据
- 使用分页或流式查询 (
StreamingQuery) - 大对象使用 DTO 投影
- 监控 JVM 堆内存和 GC 频率
Q3: 何时应该放弃 JPA 改用原生 SQL? A:
- 复杂报表查询 (多表关联、窗口函数)
- 批量数据导入导出
- 性能敏感的关键路径 (经过基准测试确认)
- 数据库特有功能 (全文搜索、地理空间)
Q4: JPA 和 MyBatis 如何选择? A:
- JPA: 领域驱动设计、快速原型、团队熟悉 OO
- MyBatis: SQL 精细控制、复杂查询、遗留系统改造
- 实际上可以混合使用: JPA 做 CRUD,MyBatis 做复杂查询
C. 推荐学习资源
- 官方文档: Spring Data JPA Reference
- Hibernate 文档: Hibernate ORM 6 Documentation
- 书籍: 《Pro Spring 6》、《Effective Java》
- 视频: Baeldung 系列教程
- GitHub: spring-data-examples
结语
Spring Boot + JPA 的强大之处在于其约定优于配置的理念和声明式编程的优雅。但正如本文反复强调的:便利性背后隐藏着复杂性。真正掌握 JPA 不仅需要知道如何写 @Entity 和 JpaRepository,更需要理解:
- 持久化上下文的运作机制 - 为什么同一个实体只会被加载一次?
- 事务边界的精确控制 - 什么时候该开启新事务?什么时候该参与现有事务?
- 性能瓶颈的系统化诊断 - 如何用 SQL 日志、Statistics、执行计划定位问题?
- 并发一致性的保障策略 - 乐观锁 vs 悲观锁的选择依据是什么?
只有将这些底层原理内化为直觉,才能在面对复杂业务场景时做出正确的技术决策,写出既高效又可靠的代码。
文档结束 | 持续更新中
