7

I'm trying to write a hibernate query to search if table Room contains roomname which contains part of string.The string value is in a variable. I wrote a query to get exact room name from the table.

findRoom(String name) {
        Query query = em.createQuery("SELECT a FROM Room a WHERE a.roomname=?1");
        query.setParameter(1, name);
        List rooms = query.getResultList();
        return rooms;
         }

In sql the query is something like this:

mysql_query("
SELECT *
FROM `table`
WHERE `column` LIKE '%"name"%' or '%"name"' or '"name"%'
");

I want to know the hql query for searching the table that matches my query. I can not use string directly, so the search query has to be veriable based and I need all three types in a query, if it's begin with name, or contains name or ends name.

2 Answers 2

9

I would do something like that:

findRoom(String name) {
        Query query = em.createQuery("SELECT a FROM Room a"
                + "WHERE a.roomname LIKE CONCAT('%',?1,'%')");
        query.setParameter(1, name);
        List rooms = query.getResultList();
        return rooms;
         }
Sign up to request clarification or add additional context in comments.

Comments

7

Use like instead of =:

Query query = em.createQuery("SELECT a FROM Room a WHERE a.roomname like ?1");

query.setParameter(1, "%"+name+"%");

4 Comments

So, %name%' or '%name' or 'name%' is not needed?! @jens
I need all three types in a query, if it's begin with name, or contains name or ends name.can you help me there?
I believe that "%"+name+"%" includes the other cases
@Mahin % stands for zero up to n characters. So this %name% includes both of the other.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.