具有CONTAINS功能的JPA Criteria api [英] JPA Criteria api with CONTAINS function

查看:790
本文介绍了具有CONTAINS功能的JPA Criteria api的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用CONTAINS函数(MS SQL)创建Criteria API查询:

I'm trying to crete Criteria API query with CONTAINS function(MS SQL):

select * from com.t_person where where(last_name,'xxx')

select * from com.t_person where contains(last_name,'xxx')

CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Person> cq = cb.createQuery(Person.class);
Root<Person> root = cq.from(Person.class);

Expression<Boolean> function = cb.function("CONTAINS", Boolean.class, 
root.<String>get("lastName"),cb.parameter(String.class, "containsCondition"));
cq.where(function);
TypedQuery<Person> query = em.createQuery(cq);
query.setParameter("containsCondition", lastName);
return query.getResultList();

但是获得异常:
org.hibernate.hql.internal.ast.QuerySyntaxException:unexpected AST节点:

But getting exception: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected AST node:

任何帮助?

推荐答案

如果你想要坚持使用 CONTAINS ,它应该是这样的:

If you want to stick with using CONTAINS, it should be something like this:

//Get criteria builder
CriteriaBuilder cb = em.getCriteriaBuilder();
//Create the CriteriaQuery for Person object
CriteriaQuery<Person> query = cb.createQuery(Person.class);

//From clause
Root<Person> personRoot = query.from(Person.class);

//Where clause
query.where(
    cb.function(
        "CONTAINS", Boolean.class, 
        //assuming 'lastName' is the property on the Person Java object that is mapped to the last_name column on the Person table.
        personRoot.<String>get("lastName"), 
        //Add a named parameter called containsCondition
        cb.parameter(String.class, "containsCondition")));

TypedQuery<Person> tq = em.createQuery(query);
tq.setParameter("containsCondition", "%näh%");
List<Person> people = tq.getResultList();

您的问题似乎缺少一些代码,所以我在做一些假设这个片段。

It seems like some of your code is missing from your question so I'm making a few assumptions in this snippet.

这篇关于具有CONTAINS功能的JPA Criteria api的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆