创建可能包含参数或可能不包含的JPA查询的最佳方法

编程入门 行业动态 更新时间:2024-10-28 20:17:14
本文介绍了创建可能包含参数或可能不包含的JPA查询的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

有创建JPA查询的方法,如下所示:

String queryString =SELECT i FROM Item i; if(null!= search){ queryString + =WHERE i.name LIKE:pattern; } TypedQuery< Item> query = entityManager.createQuery(queryString,Item.class); if(null!= search){ query.setParameter(pattern,%+ search +%); }

如果查询需要有可选的搜索字段(if null!= search) 避免重复的最常用方法是什么? 单个参数可能有两个命名查询,或者Criteria API允许避免这种情况(因为没有查询字符串),但有其他方法吗?

然后,您可以在其中添加一个可选的where子句,请参阅下面的示例:

CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery< Item> criteria = cb.createQuery(Item.class); Root< Item> root = criteria.from(Item.class); criteria.select(root); if(null!= search){ String pattern =%pattern here%; criteria.where(cb.like(root.get(name),pattern)); }

there's method that creates JPA query like this

String queryString = "SELECT i FROM Item i"; if (null != search) { queryString += " WHERE i.name LIKE :pattern"; } TypedQuery<Item> query = entityManager.createQuery(queryString, Item.class); if (null != search) { query.setParameter("pattern", "%" + search + "%"); }

and there's 2 checks if query needs to have optional search field (if null != search) what's most common way to avoid that repeat? With single parameter there could be 2 named queries, or probably Criteria API allows to avoid that (because there is no query string), but is there other ways?

解决方案

If you don't have to write the query in such a way that you're writing a query string, you could use the JPA Criteria API. You can see the class I call "ExampleDao" which I use for research and examples here.

You would then add an optional where clause to it, see example below:

CriteriaBuilder cb = entityManager.getCriteriaBuilder(); CriteriaQuery<Item> criteria = cb.createQuery(Item.class); Root<Item> root = criteria.from(Item.class); criteria.select(root); if (null != search) { String pattern = "%pattern here%"; criteria.where(cb.like(root.get("name"), pattern)); }

更多推荐

创建可能包含参数或可能不包含的JPA查询的最佳方法

本文发布于:2023-10-14 11:27:46,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:能不   或可   参数   方法   JPA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!