2013-08-28 95 views
4

我想克里特標準API查詢與CONTAINS函數(MS SQL):JPA標準API與CONTAINS功能

SELECT * FROM com.t_person其中包含(姓氏, '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:意想不到的AST節點:

任何幫助嗎?

+0

你正在使用什麼版本的hibernate? – Prabhakaran

+0

與JBOSS捆綁在一起的版本。隨意不使用Hibernate API只是JPA。 –

回答

4

如果你想堅持使用CONTAINS,它應該是這樣的:

//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(); 

看起來你的問題中缺少一些你的代碼,所以我在這段代碼中做了一些假設。

+0

我得到QuerySyntaxException:意外的AST節點:(靠近第1行,列109 [從sk.insdata.cbn.business.client.entities.Person中選擇generatedAlias0作爲generatedAlias0,其中CONTAINS(generatedAlias0.lastName,:param0)] –

+0

@petersaly Check我的編輯...我想你其實也需要一個cb.equal – FGreg

+0

我第一次嘗試:org.hibernate.exception.SQLGrammarException:'='附近的語法錯誤 –

0

你可以嘗試使用,而不是CONTAINS功能CriteriaBuilder like功能:

//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(
    //Like predicate 
    cb.like(
     //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 likeCondition 
     cb.parameter(String.class, "likeCondition"))); 

TypedQuery<Person> tq = em.createQuery(query); 
tq.setParameter("likeCondition", "%Doe%"); 
List<Person> people = tq.getResultList(); 

這將導致類似的查詢:

select p from PERSON p where p.last_name like '%Doe%'; 
+0

謝謝。但我想實現能夠進行高級搜索,如不區分重音的搜索(näh - 會找到 - nah)。 –

+0

看到我的其他答案。 – FGreg