2

How to use a prepared statement in a Hibernate query ?

E-Riz
  • 31,431
  • 9
  • 97
  • 134
user3699218
  • 81
  • 1
  • 1
  • 6
  • You need learn more about `Hibernate Queries`. You can use `native SQL query`, create `named query` using `HQL`. Look at this http://www.mkyong.com/hibernate/hibernate-parameter-binding-examples/ – OO7 Oct 16 '14 at 18:39

1 Answers1

15

By default Hibernate uses PreparedStatement. You don't have to worry about it. Not only Criteria but Hibernate uses PreparedStatement for createQuery (HQL) and createSQLQuery.

Edit

Query spSQLQuery = session.createSQLQuery("SELECT * FROM user_master WHERE user_name = :param1");
spSQLQuery.setString("param1","vicky.thakor");
spSQLQuery.list();

Update

Use setParameter if setString is not there in Query interface.

Thank you @Agricola for the update.

Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67
  • SELECT gl_acc_no,SUM(case when debit_credit = '56' then local_currency end) Debit, SUM(case when debit_credit = '57' then local_currency end) Credit, count(case when debit_credit='57' then debit_credit end) CreditCount, count(case when debit_credit='56' then debit_credit end) DebitCount FROM wee_fas_transaction_detail_det where document_no in('1643','1644','1645','1646','1647','1648','1649','1650','1651','1652','1653','1654','1655','1656','1657') GROUP BY gl_acc_no; This is my query how to return multiple coluumn values in java – user3699218 Oct 17 '14 at 12:07
  • If you are creating query by appending string then it'll be cached in same manner if some data changed in above query then it'll be cached again.. use `setParameter`, `setString`, etc... – Vicky Thakor Oct 17 '14 at 12:09
  • can u give me example for this i can understand easly – user3699218 Oct 17 '14 at 12:11
  • Does it mean all queries in Hibernate are pre-compiled as PreparedStaetment? – Arun Raaj Sep 17 '18 at 14:31
  • 3
    setString has been deprecated since 5.2. The documentation recommends using setParameter instead. – Agricola Oct 18 '19 at 14:58