4

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)

1 Answer 1

8

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.