I have a similar question. I am doing an INSERT and SELECT in a named SQL query and trying to execute the same with Query.uniqueResult(). The following is my named query definition:
<sql-query name="QRY_ADD_FOO_ITEM" >
<return-scalar column="id" type="integer"/>
<![CDATA[
INSERT INTO foo_items (col1, col2, col3, col4)
VALUES (:col1, :col2, :col3, :col4);
SELECT @@IDENTITY AS id;
]]>
</sql-query>
Now in my DAO, I am trying to insert and retrieve this using:
public int saveFooItem(final Foo fooToSave) throws DataAccessException {
return (Integer)getHibernateTemplate().execute(new HibernateCallback() {
/* (non-Javadoc)
* @see org.springframework.orm.hibernate3.HibernateCallback#doInHibernate(org.hibernate.Session)
*/
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Query qry = session.getNamedQuery("QRY_ADD_FOO_ITEM");
qry.setString("col1", prefSection.getCol1());
qry.setInteger("col2", prefSection.getCol2());
qry.setInteger("col3", prefSection.getCol3());
qry.setString("col4", prefSection.getCol4());
int retVal = ((Integer)qry.uniqueResult()).intValue();
session.flush();
return retVal;
}
});
}
I wanted save the Foo item into the table and retrieve its auto-generated ID. That is the reason I combined both these INSERT and SELECT operations into one query and used uniqueResult() to retrieve the ID value. I agree this may not be the best way to do it.
Now the problem is, I am finding that in most cases the Foo item gets inserted into the table but sometimes fails to insert the data item and does not even report an error.
Please let me know what I can do.
P.S. I am using Hibernate 3.0.5 with Spring 2.0 with SQL Server 2005