views:

190

answers:

1

I am using Hibernate in my project and there is a certain scenario where I want to use the uniqueResult() method on the org.hibernate.SQLQuery class to perform native SQL INSERT and UPDATE operations.

I did try using the executeUpdate() method on the same class. But I get an error saying that they are used for HQL updates only.

Please advice if this is effective and reliable way of ensuring data being saved/updated in the database.

A: 

session.createSQLQuery() is for querying, not manipulation. If you want to do raw SQL insert, use session.connection() and straight JDBC code.

Not sure why you need this exactly but I'd also suggest to check 16.3. Custom SQL for create, update and delete.

Pascal Thivent
Thanks Pascal. But, would session.connection() work within the transaction boundaries of the current Hibernate Session?Actually I want to execute the native SQL for some inserts and updates and need to do it with raw SQL for performance reasons. Besides i'm working with a database whose schema is not designed/optimized on entities and so I have trouble getting Hibernate to work well with it.I am doing some inserts using uniqueResults(), it works for most places but fails to insert data in some cases. Hence I wanted to do it the old-school JDBC way.
Ranganath Kini
@RanganathKini: `session.connection()` returns the underlying JDBC connection so, yes, it will work within the boundaries of the current transaction.
Pascal Thivent