I'm trying to use hibernate to make a simple SQL UPDATE query and map the result row into Hibernate entity (Using the createSQLQuery
).
String updateQuery =
String.format("UPDATE \"user\" "
+ "SET chips_balance=chips_balance + %d, diamonds_balance=diamonds_balance + %d "
+ "WHERE id=%d", chips_delta, diamonds_delta, userId);
User user = (User)session.createSQLQuery(updateQuery).uniqueResult();
This throws an Exception:
org.hibernate.exception.GenericJDBCException: could not extract ResultSet
Cause:
org.postgresql.util.PSQLException: No results were returned by the query.
How can I make this work? (Using the RETURNING
keyword)
This is how to achieve it:
String updateQuery =
String.format( "UPDATE \"user\" "
+ "SET chips_balance=chips_balance + %d, diamonds_balance=diamonds_balance + %d "
+ "WHERE id=%d "
+ "RETURNING *", 100, 5, 64);
User user = (User) session.createSQLQuery(updateQuery)
.addEntity(User.class)
.uniqueResult();
The key point here is to use "RETURNING *" and map it to the entity using .addEntity(User.class)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With