JPA Criteria api with CONTAINS function

前端 未结 2 1057
星月不相逢
星月不相逢 2020-12-18 02:14

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

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

CriteriaBuilder          


        
相关标签:
2条回答
  • 2020-12-18 02:45

    You could try using the CriteriaBuilder like function instead of the CONTAINS function:

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

    This should result in a query similar to:

    select p from PERSON p where p.last_name like '%Doe%';
    
    0 讨论(0)
  • 2020-12-18 02:54

    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.

    0 讨论(0)
提交回复
热议问题