# Java Jpa Hibernate

> Master JPA/Hibernate - entity design, queries, transactions, performance optimization

- **Type:** Skill
- **Install:** `agentstack add skill-linlannet-agent-skills-java-jpa-hibernate`
- **Verified:** Yes — security-reviewed for prompt injection and unsafe behavior
- **Seller:** [linlannet](https://agentstack.voostack.com/s/linlannet)
- **Installs:** 0
- **Category:** [Agent Skills](https://agentstack.voostack.com/c/agent-skills)
- **Latest version:** 0.1.0
- **License:** Apache-2.0
- **Upstream author:** [linlannet](https://github.com/linlannet)
- **Source:** https://github.com/linlannet/agent-skills/tree/main/skills/java-jpa-hibernate

## Install

```sh
agentstack add skill-linlannet-agent-skills-java-jpa-hibernate
```

Requires the [AgentStack CLI](https://agentstack.voostack.com/docs/cli). Works with Claude Code, Cursor, and any MCP-compatible agent.

## About

# Java JPA Hibernate 技能

掌握使用JPA和Hibernate进行生产应用程序的数据持久化。

## 概述

此技能涵盖JPA实体设计、Hibernate优化、Spring Data存储库、查询策略和缓存。专注于防止N+1查询和构建高性能持久化层。

## 何时使用此技能

当您需要：
- 设计带有关系的JPA实体
- 优化数据库查询
- 配置Hibernate以提高性能
- 实现缓存策略
- 调试持久化问题

## 涵盖的主题

### 实体设计
- 实体映射注解
- 关系类型（1:1, 1:N, N:M）
- 继承策略
- 生命周期回调
- 审计

### 查询优化
- N+1问题预防
- JOIN FETCH vs EntityGraph
- 批量获取
- 投影和DTO

### 事务
- @Transactional配置
- 传播和隔离
- 乐观锁vs悲观锁
- 死锁预防

### 缓存
- 一级和二级缓存
- 查询缓存
- 缓存失效
- Redis集成

## 快速参考

```java
// 带有关系的实体
@Entity
@Table(name = "orders")
public class Order {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "customer_id", nullable = false)
    private Customer customer;

    @OneToMany(mappedBy = "order", cascade = CascadeType.ALL, orphanRemoval = true)
    @BatchSize(size = 20)
    private List items = new ArrayList<>();

    @Version
    private Long version;

    // 双向关系辅助方法
    public void addItem(OrderItem item) {
        items.add(item);
        item.setOrder(this);
    }
}

// 审计基类
@MappedSuperclass
@EntityListeners(AuditingEntityListener.class)
public abstract class Auditable {
    @CreatedDate
    @Column(updatable = false)
    private Instant createdAt;

    @LastModifiedDate
    private Instant updatedAt;
}

// 带有查询优化的存储库
public interface OrderRepository extends JpaRepository {

    // JOIN FETCH 防止N+1
    @Query("SELECT DISTINCT o FROM Order o JOIN FETCH o.items WHERE o.status = :status")
    List findByStatusWithItems(@Param("status") Status status);

    // EntityGraph替代方案
    @EntityGraph(attributePaths = {"items", "customer"})
    Optional findById(Long id);

    // DTO投影
    @Query("SELECT new com.example.OrderSummary(o.id, o.status, c.name) " +
           "FROM Order o JOIN o.customer c WHERE o.id = :id")
    Optional findSummaryById(@Param("id") Long id);
}
```

## N+1预防策略

| 策略 | 使用场景 | 示例 |
|------|----------|------|
| JOIN FETCH | 始终需要关系 | `JOIN FETCH o.items` |
| EntityGraph | 动态获取 | `@EntityGraph(attributePaths)` |
| @BatchSize | 集合访问 | `@BatchSize(size = 20)` |
| DTO投影 | 只读查询 | `new OrderSummary(...)` |

## Hibernate配置

```yaml
spring:
  jpa:
    open-in-view: false  # 关键！
    properties:
      hibernate:
        jdbc.batch_size: 50
        order_inserts: true
        order_updates: true
        default_batch_fetch_size: 20
        generate_statistics: ${HIBERNATE_STATS:false}

  datasource:
    hikari:
      maximum-pool-size: 20
      minimum-idle: 5
      leak-detection-threshold: 60000
```

## 故障排除

### 常见问题

| 问题 | 原因 | 解决方案 |
|------|------|----------|
| N+1查询 | 循环中的延迟加载 | JOIN FETCH, EntityGraph |
| LazyInitException | 会话关闭 | DTO投影 |
| 查询缓慢 | 缺少索引 | EXPLAIN ANALYZE |
| 连接泄漏 | 无@Transactional | 添加注解 |

### 调试属性
```properties
spring.jpa.show-sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.orm.jdbc.bind=TRACE
hibernate.generate_statistics=true
```

### 调试清单
```
□ 启用SQL日志
□ 检查每个请求的查询计数
□ 验证获取策略
□ 审查@Transactional
□ 检查连接池
```

## 使用

```
Skill("java-jpa-hibernate")
```

## 相关技能
- `java-performance` - 查询优化
- `java-spring-boot` - Spring Data

## Source & license

This open-source skill is cataloged on AgentStack and links to its original source — we do not rehost the code.

- **Author:** [linlannet](https://github.com/linlannet)
- **Source:** [linlannet/agent-skills](https://github.com/linlannet/agent-skills)
- **License:** Apache-2.0

Install and usage instructions live in the source repository linked above.

## Pricing

- **Free** — Free

## Security capabilities

Automated source analysis of v0.1.0 — what this tool can access:

- **Network access:** no
- **Filesystem access:** no
- **Shell / process execution:** no
- **Environment & secrets:** no
- **Dynamic code execution:** no

*"Yes" means the capability is present in the source — more access means more to trust, not that it is unsafe.*


## Versions

- **0.1.0** — security scan: passed — Imported from the upstream source.

## Links

- Listing page: https://agentstack.voostack.com/l/skill-linlannet-agent-skills-java-jpa-hibernate
- Seller: https://agentstack.voostack.com/s/linlannet
- Browse the marketplace: https://agentstack.voostack.com/browse

---
Listed on AgentStack — the marketplace for AI agent skills and MCP servers. Every listing is security-reviewed. Creators keep 70%.
