Hibernate "Session resource type does not implement java.lang.AutoCloseable"

I want to use the construction

import org.hibernate.Session;
...
try (Session session){

}

      

How can i do this? Because "The Session resource type does not implement java.lang.AutoCloseable"

I know that I need to extend Session and override the AutoCloseable method, but when I try to do this, the error "Session type cannot be a superclass of SessionDAO, superclass must be a class"

Update

I wrote my own DAO framework but will use Spring to do this

+3


source to share


1 answer


First, you have to use a much more robust session / transaction processing framework like Spring offers you. This way, you can use the same session for multiple DAO calls, and the transaction boundary is explicitly set by the @Transactional annotation.

If this is for your test project, you can use a simple utility like:

protected <T> T doInTransaction(TransactionCallable<T> callable) {
    T result = null;
    Session session = null;
    Transaction txn = null;
    try {
        session = sf.openSession();
        txn = session.beginTransaction();

        result = callable.execute(session);
        txn.commit();
    } catch (RuntimeException e) {
        if ( txn != null && txn.isActive() ) txn.rollback();
        throw e;
    } finally {
        if (session != null) {
            session.close();
        }
    }
    return result;
}

      



And you can call it like this:

final Long parentId = doInTransaction(new TransactionCallable<Long>() {
        @Override
        public Long execute(Session session) {
            Parent parent = new Parent();
            Child son = new Child("Bob");
            Child daughter = new Child("Alice");
            parent.addChild(son);
            parent.addChild(daughter);
            session.persist(parent);
            session.flush();
            return parent.getId();
        }
});

      

Check out this GitHub repository for more examples like this one.

+2


source







All Articles