Search code examples
javamysqlhibernateapostrophe

QueryException in Hibernate because of apostrophe


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?


Solution

  • 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