有创建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查询的最佳方法
发布评论