JPQL query for searching if a word/string is consisted in one of entity's fields

你说的曾经没有我的故事 提交于 2019-12-10 17:23:54

问题


Basicaly, its similar like looking if certain word exists in sentence. There is entity Post:

public class Post implements Serializable {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "post_id", unique = true, nullable = false)
    private Integer id; 

    @Column(name = "post_title", length=300, unique = false, nullable = false)
    private String title;

    @Column(name = "post_date", unique = false, nullable = false)
    private Date date;
        ...}

I am trying to implement JPQL query that will search for Post entity instances that have certain word/string ( byTitle, passed as an argument) in their title field, and two more arguments of Date type, that represents date range - startDate and endDate.

I have something like this on my mind: SELECT p FROM Post p WHERE :byTitle IN (set of strings created from parsing p.title field) AND p.date>=:startDate AND p.date<=endDate

How to implement this kind of JPQL query? Or maybe JPA Criteria API should be used?

EDIT: Like there is someString.contains(someSubstring) function in Java, is there anything similar in JPQL? Or Criteria API? And for comparing, it doesn't have to be case sensitive.


回答1:


I have implemented it using JPQL LIKE paired with pattern expression:

SELECT p FROM Post p WHERE 
       p.title LIKE :pattern AND 
               p.date>=:startDate AND 
                     p.date<=:endDate

where pattern = "%" + someString + "%".




回答2:


I think you must use several LIKE clauses connected by OR:

WHERE (p.title LIKE :firstWord OR ... OR p.title LIKE :lastWord) AND p.date >= :startDate AND p.date <= :endDate

and then set parameters:

query.setParameter("firstWord", '%' + firstWord + '%');
...
query.setParameter("lastWord", '%' + lastWord + '%');

But the query may be slow. You can consider using a dedicated fulltext search tool like Hibernate Search.



来源:https://stackoverflow.com/questions/21137719/jpql-query-for-searching-if-a-word-string-is-consisted-in-one-of-entitys-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!