java - HQL: Handling special characters -
java - HQL: Handling special characters -
i trying fetch value database using hql
getting exceptions because value contains special characters. not able figure out why.
below code trying:
hotelmapping hotelmapping = null; sessionfactory sessionfactory = hibernateutil.getsessionfactory(); session session = sessionfactory.opensession(); transaction tx = session.gettransaction(); tx.begin(); string hotelname = "a fisher's inn motel"; query query = session.createquery("from hotelmapping hm hm.hotelid.hotelname='"+hotelname+"'"); hotelmapping mapping = query.uniqueresult(); } tx.rollback(); sessionfactory.close();
the pojos below: hotel.java
public class hotel{ string hotelname; double price; //getters , setters }
hotelmapping.java
public class hotelmapping{ @onetoone(cascade = cascadetype.all) hotel hoteid string location; }
the query string
query query = session.createquery("from hotelmapping hm hm.hotelid.hotelname='"+hotelname+"'");
gives me below exception :
exception in thread "main" org.hibernate.queryexception: expecting ''', found '<eof>' [from com.pb.model.hotelmapping hm hm.hotelid.hotelname='a fisher's inn motel']
i tried escaping apostrophe no luck. ven tried setting query parameter 1 time again got exception
query.setparameter("hotelname", "a fisher's inn motel");
it says exception in thread "main" org.hibernate.queryparameterexception: not locate named parameter [hotelname]
please if help me achieving generalized solution special character handling?
you should never utilize concatenation pass dynamic parameters this. not not efficient, not robust (since single quote in parameter value makes query invalid) , insecure, since malicious user pass value changes semantics of query (google "sql injection attack").
instead, utilize parameters:
query query = session.createquery( "from hotelmapping hm hm.hotelid.hotelname = :hotelname"); query.setstring("hotelname", hotelname);
java sql hibernate hql
Comments
Post a Comment