由于撇号,Hibernate中的QueryException [英] QueryException in Hibernate because of apostrophe
问题描述
这里是我的查询
SQL_QUERY =SELECT review.comment FROM ReviewDO review WHERE title ='+ titleName +' ;
通过使用标题试图获得它的描述。
For 示例 if tileName =Worth for money;
(无撇号)查询将为:
SQL_QUERY =SELECT review.comment FROM ReviewDO review WHERE title ='Worth for money';
得到输出结果。
但如果 titleName =Can not击败产品;
(带撇号)
SQL_QUERY =SELECT review.comment FROM ReviewDO review WHERE title ='无法击败产品';
得到 org.hibernate.QueryException:期待''',找到'EOF'
有什么办法可以避免这个问题吗?
使用占位符。它还将有助于防止SQL注入:
Session ses = HibernateUtil.getSessionFactory()。openSession();
String query =SELECT review.comment FROM ReviewDO review WHERE title =:title;
列表< ReviewComment> reviewComments = ses.createQuery(query)
.setParameter(title,Can not beat the product)
.list();
ses.close();
如果您确定您的查询只给出一条记录,那么不要使用list()查询接口的uniqueResult()方法。
有关更多详细信息,请参阅Query接口的文档这里
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?
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
这篇关于由于撇号,Hibernate中的QueryException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!