Skip to content
Advertisement

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?

Advertisement

Answer

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>() {

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

log.info("Found " + bookCount + " books.");
Advertisement