Skip to content

What is the purpose of the Hibernate ReturningWork interface?

I am working on one JAVA + Hibernate project but currently, I saw one interface in my code (i.e. ReturningWork<Long>) which has one method called execute(java.sql.Connection).

My question is what is the use of this ReturningWork interface?


As I explained in more details on my blog, you can use the ReturningWork and the Work interfaces to implement any logic that requires direct access to the java.sql.Connection used by your Hibernate session.

Here is a simple example that uses the ReturningWork interface to execute a very simple query (which you could also implement with JPQL) and return the result.

Session session = em.unwrap(Session.class);
Integer bookCount = session.doReturningWork(new ReturningWork<Integer>() {

    public Integer execute(Connection con) throws SQLException {
        // do something useful
        try (PreparedStatement stmt = con.prepareStatement("SELECT count( FROM Book b")) {
            ResultSet rs = stmt.executeQuery();
            return rs.getInt(1);
});"Found " + bookCount + " books.");