Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hibernate query for searching part of string

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.

like image 711
Mahin Avatar asked Feb 17 '15 06:02

Mahin


People also ask

How write HQL query for inner join?

We can also create alias such as from Employee emp or from Employee as emp . HQL Join : HQL supports inner join, left outer join, right outer join and full join. For example, select e.name, a. city from Employee e INNER JOIN e.


2 Answers

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;
         }
like image 104
Maurice Perry Avatar answered Nov 12 '22 17:11

Maurice Perry


Use like instead of =:

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

query.setParameter(1, "%"+name+"%");
like image 6
Jens Avatar answered Nov 12 '22 17:11

Jens