JPQL 通过精确数组匹配查找实体
JPQL find entity by exact array match
我的实体 Monitor
包含属性 categories
,它是实体 Category
的集合。是否可以使用 JPQL 通过 Categories
的集合来查找实体 Monitor
?
像这样:
@Query("SELECT m from Monitor m where m.categories = :cats")
Monitor findByCategories(@Param("cats") Set<MessageCategory> cats);
此代码段引发错误 com.impossibl.postgres.jdbc.PGSQLSimpleException: syntax error at or near "."
提前致谢
如果你的Monitor只有一个类别,那么你可以在查询中使用IN子句:
@Query("SELECT m from Monitor m where m.categories IN :cats")
但是如果您的 Monitor.categories 字段是一个列表,这将不起作用。应该有更复杂的逻辑。
2017 年 8 月 11 日更新:
正如我在评论中所写,您可以将类别 ID 列表转换为一个字符串并与另一个字符串进行比较。对于这种情况,最好的方法是创建一个视图,但不幸的是,这个决定取决于 SQL-engine。对于 PostgreSQL 你可以使用这样的东西:
select m.*, string_agg(mc.catid, ',') as catids
FROM monitor as m
LEFT JOIN messagecategories as mc on mc.monitor_id = m.id
GROUP BY m.id;
我的实体 Monitor
包含属性 categories
,它是实体 Category
的集合。是否可以使用 JPQL 通过 Categories
的集合来查找实体 Monitor
?
像这样:
@Query("SELECT m from Monitor m where m.categories = :cats")
Monitor findByCategories(@Param("cats") Set<MessageCategory> cats);
此代码段引发错误 com.impossibl.postgres.jdbc.PGSQLSimpleException: syntax error at or near "."
提前致谢
如果你的Monitor只有一个类别,那么你可以在查询中使用IN子句:
@Query("SELECT m from Monitor m where m.categories IN :cats")
但是如果您的 Monitor.categories 字段是一个列表,这将不起作用。应该有更复杂的逻辑。
2017 年 8 月 11 日更新: 正如我在评论中所写,您可以将类别 ID 列表转换为一个字符串并与另一个字符串进行比较。对于这种情况,最好的方法是创建一个视图,但不幸的是,这个决定取决于 SQL-engine。对于 PostgreSQL 你可以使用这样的东西:
select m.*, string_agg(mc.catid, ',') as catids
FROM monitor as m
LEFT JOIN messagecategories as mc on mc.monitor_id = m.id
GROUP BY m.id;