Hibernate hql like query has special characters

Source: Internet
Author: User
Hibernate query special characters such as % _

In SQL, %, _ and so on are special characters. Sometimes we need to query these special characters and escape them. The following two sentences are escaped.

Select username from gg_user where username like '% Xiao/_ %' escape '/';

Select username from gg_user where username like '% Xiao/%' escape '/';

The first SQL statement means that the _ after/is no longer used as a special character, and the second SQL statement means that the % after/is no longer used as a special character.

I listed my own piece of code in hibernate:

Public List Search (string username, string key, int page, int max ){
// Todo auto-generated method stub
Session session = hibernatesessionfactory. getsession ();
String hql = "from content c Where C. username in (select T. attenuser from attention t where T. Username = ?) And
C. Text like? Escape '/'order by C. Time DESC ";
Query q = session. createquery (hql );
Q. setstring (0, username );
Key = key. replaceall ("%", "/% ");
Key = key. replaceall ("_","/_");
Q. setstring (1, "%" + key + "% ");
Q. setmaxresults (max );
Q. setfirstresult (page-1) * max );
List list = Q. List ();
Session. Close ();
Return list;
 
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.