ing Data JPA 派生方法 数据操作速查表
📘 Spring Data JPA 速查表
🔍 1. 查询(Query Methods)
派生方法支持 find
/ read
/ get
开头。
关键字 | 示例方法 | SQL 效果 |
---|---|---|
findBy | findByName(String name) | where name = ? |
And / Or | findByNameAndAge(String n, int a) | where name = ? and age = ? |
Between | findByAgeBetween(int s, int e) | where age between ? and ? |
LessThan / Gt | findByAgeLessThan(int max) | where age < ? |
Like | findByNameLike(String n) | where name like ? |
Containing | findByNameContaining(String k) | where name like %?% |
StartingWith | findByNameStartingWith(String p) | where name like '?%' |
EndingWith | findByNameEndingWith(String s) | where name like '%?' |
In / NotIn | findByIdIn(List<Long> ids) | where id in (?) |
IsNull / NotNull | findByDeletedAtIsNull() | where deleted_at is null |
True / False | findByActiveTrue() | where active = true |
IgnoreCase | findByNameIgnoreCase(String n) | lower(name) = lower(?) |
OrderBy | findByOrgIdOrderByCreatedAtDesc(id) | order by created_at desc |
Top / First | findTop10ByOrderByScoreDesc() | limit 10 |
Distinct | findDistinctByOrgId(String org) | select distinct … |
✍️ 2. 插入 & 更新(Insert / Update)
JPA 没有专门的派生 insert
/ update
方法,但常见方式有:
2.1 save / saveAll
repo.save(entity); // 插入或更新
repo.saveAll(list); // 批量插入或更新
- insert:主键不存在 → 插入
- update:主键存在 → 更新
2.2 @Modifying + @Query(手写更新)
@Modifying
@Query("update User u set u.status = ?2 where u.id = ?1")
int updateStatus(Long id, int status);
👉 适合更新部分字段。
2.3 批量更新
saveAll()
内部循环调用 SQL(不是原生批量)- 真正批量更新 → 建议
@Modifying @Query
或JdbcTemplate
/批量 SQL
🗑️ 3. 删除(Delete)
3.1 单个 / 按条件删除
方法名 | SQL 效果 |
---|---|
deleteById(Long id) | delete from table where id = ? |
deleteByUserId(String uid) | delete from table where user_id=? |
deleteByStatus(int s) | delete from table where status=? |
deleteAllByOrgTag(String o) | delete from table where org_tag=? |
⚠️ 注意:
deleteByXxx
直接生成DELETE
SQL,不会触发@PreRemove
等生命周期回调。
3.2 批量删除
repo.deleteAllInBatch(); // 清空表
repo.deleteAllByIdInBatch(List<ID> ids); // 按主键批量删
repo.deleteAll(list); // 循环删除(逐条)
⚡ 4. 批量处理总结
操作 | 推荐方法 | 特点 |
---|---|---|
批量插入/更新 | saveAll(list) | 内部逐条 SQL,非真正批量 |
批量更新 | @Modifying @Query / 原生 SQL | 高效,支持部分字段更新 |
批量删除 | deleteAllInBatch() / deleteAllByIdInBatch() | 直接批量 delete,效率高 |
✅ 5. 实战推荐
- 查询 →
findByXxx
(简单) +@Query
(复杂) - 插入/更新 →
save
/saveAll
- 删除 →
deleteByXxx
(单条件) /deleteAllInBatch
(批量) - 部分字段更新 →
@Modifying @Query
- 真正大批量 → 建议走
JdbcTemplate
或原生 SQL(性能更好)