Pregunta

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.

¿Fue útil?

Solución

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 + "%".

Otros consejos

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top