Escape quote in HQL query

2019-08-08 17:10发布

问题:

I'm developping an application with spring mvc and hibernate, i have a problem in my hql query when i want to select an object from the database by his name.

Because the name contain a quote (ingénieur d'étude)

String hql = "From Intervenant I Where I.profil like '"+profil+"'";

i had this exception :

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.QueryException: expecting ''', found '<EOF>' [From com.model.Intervenant I Where I.profil like 'Ingénieur d'étude']

Is the user who inserts datas, so how I can know what the user inserted and where it has put the quote or any other special caracters ?

Please can you help me !

回答1:

Put single quote to escaping charater in mysql like following

profile = ingénieur d''étude;

OR

profile = ingénieur d\'étude;