Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Hibernate entity on UPDATE query

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)

like image 745
Shvalb Avatar asked Feb 08 '23 18:02

Shvalb


1 Answers

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)

like image 160
Shvalb Avatar answered Feb 12 '23 11:02

Shvalb