- 第一我很蠢。
- 第二 SQL 的世界是复杂的,而 JPA 是单纯的。
比如根据标签找用户:
表设计如下
- 用户表
- 用户标签表
- 标签表
sql 很好写(使用的是 postgresql):
select c.id,c.username
from client_customer c
inner join client_custom_and_label cl on c.id= cl.custom_id
inner join client_label l on cl.label_id=l.id
group by c.id
having array_agg(l.id) @> array[65,67]
但是 jpa 里面:
@Query(nativeQuery = true,value = "select c.id,c.username\n" +
"from client_customer c\n" +
"inner join client_custom_and_label cl on c.id= cl.custom_id\n" +
"inner join client_label l on cl.label_id=l.id\n" +
"group by c.id\n" +
"having array_agg(l.id) @> array[:list]")
List<Map<String,Object[]>> findByLabelId(@Param("list") List<Integer> list);
当 list 的 size 等于 1 的时候非常好写,但是大于 1 的时候自动加了括号 array[(?, ?, ?)]:
Hibernate: select c.id,c.username
from client_customer c
inner join client_custom_and_label cl on c.id= cl.custom_id
inner join client_label l on cl.label_id=l.id
group by c.id
having array_agg(l.id) @> array[(?, ?, ?)]