QueryException in Hibernate because of apostrophe

大城市里の小女人 提交于 2019-12-08 12:35:01

问题


Here its my Query

SQL_QUERY="SELECT review.comment FROM ReviewDO review WHERE title='"+titleName+"'";

By using title am trying to get its description.

For Example if tileName="Worth for money"; (without apostrophe) the query will be:

SQL_QUERY="SELECT review.comment FROM ReviewDO review WHERE title='Worth for money';

am getting the output.

but if titleName="Can't beat the product";(with apostrophe)

SQL_QUERY="SELECT review.comment FROM ReviewDO review WHERE title='Can't beat the product';

am getting org.hibernate.QueryException:expecting ''',found 'EOF'

Is there any way to avoid this problem?


回答1:


Use placeholders. It will also help in preventing SQL injections:

 Session ses = HibernateUtil.getSessionFactory().openSession();
  String query = "SELECT review.comment FROM ReviewDO review WHERE title=:title";
  List<ReviewComment> reviewComments = ses.createQuery(query)
  .setParameter("title", "Can't beat the product")
  .list();
  ses.close();

And if you are sure that your query will give only one record then instead of using list() use uniqueResult() method of Query interface.

For more details see the documentation of Query interface here




回答2:


You can use PreparedStatement instead of simple query and let PreparedStatement handles apostrophe and other special characters for you. Refer this Oracle's documentation.

Second way is to use StringEscapeUtils library. Refer the doc.



来源:https://stackoverflow.com/questions/19651322/queryexception-in-hibernate-because-of-apostrophe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!