Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a like query in HQL [duplicate]

Tags:

I want to perform search for a particular string that is starting with a particular alphabet.

So, for example if the starting alphabet is 'A' then it should produce a result which will contain all the strings with alphabet 'A'.

How do I achieve this ?

My query is as shown below:

Query qry = session.createQuery("From RegistrationBean as rb where rb."+searchCriteria+"  like %?%"); qry.setString(0,searchField); 
like image 440
Ni3 Avatar asked Nov 26 '12 09:11

Ni3


People also ask

How do you use like clause in HQL?

Well, LIKE operator is usually used with textual data i.e. with VARCHAR or CHAR columns, and you have numeric id column (INTEGER). Maybe you could try to map id field also as string and use that field in query. This may or may not work depending on your database engine.

Can we use select * in HQL?

Keywords like SELECT, FROM, and WHERE, etc., are not case sensitive, but properties like table and column names are case sensitive in HQL.

How can I get distinct records in Hibernate?

You can add the DISTINCT keyword to your query to tell Hibernate to return each Author entity only once. But as you can see in the following log messages, Hibernate also adds the DISTINCT keyword to the SQL query. This is often not intended and might result in an efficient database query.


2 Answers

Change your query to this:

Query qry = session.createQuery("From RegistrationBean as rb where rb."+searchCriteria+"  like ?"); qry.setString(0, "%"+searchField+"%"); 
like image 70
Aleksandr M Avatar answered Oct 20 '22 01:10

Aleksandr M


You can use criteria for using like

session = sessionFactory.openSession(); Criteria query = session.createCriteria(Pojo.class); query.add(Restrictions.like("column", "a", MatchMode.START)); 

It will give you the list of string which start by alpha-bate 'a'.

like image 42
MayurB Avatar answered Oct 19 '22 23:10

MayurB