7

I'm using createSQLQuery with setString (No hard coded value) in Hibernate. I want to know that is Hibernate uses PreparedStatement for createSQLQuery?

Concern:

I want to preserve the execution plan created by this query in cache so next time same query fired on database, It would use same execution plan.

FYI: I'm using MSSQL Server 2008

/* This is just example I'm not using same query */
Query nativeSQLQuery = session.createSQLQuery("select Firstname from user_master where user_name = :param");
nativeSQLQuery.setString("param", "vicky.thakor");

I couldn't find stackoverflow link or even in google so please provide me link if any.

Vicky Thakor
  • 3,847
  • 7
  • 42
  • 67

2 Answers2

10

I have tried to execute a query using Hibernates' createSQLQuery method then it will give me exception as below :-

at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2275)
at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:186)
at org.hibernate.loader.Loader.getResultSet(Loader.java:1787)
at org.hibernate.loader.Loader.doQuery(Loader.java:674)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:236)
at org.hibernate.loader.Loader.doList(Loader.java:2220)

From the above exception we can see that it will try to execute com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2275) internally.

I have also found a question by @Alex Serna at Hibernate createSQLQuery parameter substitution where Alex also get the exception while trying to substitute table name.

Observing stack trace I think Hibernate uses PreparedStatement for createSQLQuery internally.

OO7
  • 2,785
  • 1
  • 21
  • 33
  • Its one of the weird way to answer the question but I like the way... I found another way that proves hibernate uses PreparedStatement. Thanks anyway. – Vicky Thakor Aug 04 '14 at 05:33
  • Execute `DBCC FREEPROCCACHE DBCC DROPCLEANBUFFERS GO` at SQL Server then execute any `select` query in hibernate and after that execute `SELECT usecounts, size_in_bytes, cacheobjtype, text FROM sys.dm_exec_cached_plans CROSS APPLY sys.dm_exec_sql_text(plan_handle) WHERE cacheobjtype != 'Parse Tree'` in SQL server. – Vicky Thakor Aug 06 '14 at 05:33
1

Hibernate SQLQuery bypasses the Hibernate Session cache and queries ONLY against the database. You can read more @ Hibernate: SQL vs HQL with the Session Cache.

Amogh
  • 4,453
  • 11
  • 45
  • 106