Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do Hibernate query using like and %?

I have a Hibernate SQL query like this:

public void funcA(String str) {
  StringBuilder sql = new StringBuilder();
  sql.append("select fieldA from tableA where fieldB like '%:searchKey%'");

  ...

  session.createSQLQuery(sql.toString())
  .addScalar("fieldA", StandardBasicTypes.STRING)
  .setParameter("searchKey", str);

  ...
}

when I make a query like this query.list(), I got following error:

[WARNING ] SQL Error: -7, SQLState: 42601[ERROR   ] The character "%" following "fieldB like" is not valid.
[ERROR   ] An error occurred during implicit system action type "2".  Information returned for the error includes SQLCODE "-7", SQLSTATE "42601" and message tokens "%|fieldB like".

May I know how could I solve this problem?

like image 806
huahsin68 Avatar asked Aug 15 '12 09:08

huahsin68


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.

What is query uniqueResult () in hibernate?

uniqueResult. Convenience method to return a single instance that matches the query, or null if the query returns no results.

How many ways we can write query in hibernate?

To create query in the Hibernate ORM framework, there is three different types.


1 Answers

this should work:

    public void funcA(String str) {
  StringBuilder sql = new StringBuilder();
  sql.append("select fieldA from tableA where fieldB like :searchKey");

  ...

  session.createSQLQuery(sql.toString())
  .addScalar("fieldA", StandardBasicTypes.STRING)
  .setParameter("searchKey", "%" + str + "%");

  ...
}
like image 153
Denis Zevakhin Avatar answered Oct 22 '22 10:10

Denis Zevakhin