3

I want to use construction

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

}

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

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

Update

I've wrote my own DAO framework, but will be use Spring for that

3

1 Answer 1

2

First, you should use a much more solid session/transaction handling infrastructure, like Spring offers you. This way you can use the Same Session across multiple DAO calls and the transaction boundary is explicitly set by the @Transactional annotation.

If this is for a test project of yours, you can use a simple utility like this one:

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 this GitHub repository for more examples like this one.

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.