一些背景知识 - 我使用的是 Hibernate 3.5(最相关的是,它没有联合。)我有 Items,并且有 Tags。标签作为集合存储在项目中。我正在尝试编辑我们的数据库搜索组件,以便我可以通过字符串搜索项目,该字符串可以是项目名称或标签名称。实际上,我有两个疑问:
select a from Item a where a.name = :searchString;
select a from Item a join a.tags t where t.name = :searchString;
对我来说最明显的组合它们的方式是:
select a from Item a where a.name = :searchString or a.id in (select b.id from Item b join b.tags t where t.name = :searchString);
这会产生正确的结果 - 但是,它生成的 SQL 会导致我们的 MySQL 数据库对 Item 执行全表扫描。两个单独的查询都不会这样做——而是添加了“in”子句导致了扫描。对我来说,执行两个单独的 hql 选择并在结果集上用 Java 代码执行“穷人联合”可能并不理想,因为这需要对我们的搜索功能进行彻底的代码更改。但是,如果无法访问联合,我就无法找到组合查询的其他方法。任何帮助将不胜感激。
最佳答案
你不能只使用左外连接标签
并或保留不同的值吗?像这样
select distinct a
from Item a left outer join a.tags t
where t.name = :searchString or a.name=:searchString;
关于java - 组合 Hibernate 查询而不进行表扫描,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33247339/