【问题标题】:Hibernate "The resource type Session does not implement java.lang.AutoCloseable"Hibernate“资源类型Session没有实现java.lang.AutoCloseable”
【发布时间】:2015-02-08 10:20:06
【问题描述】:

我想用建筑

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

}

我该怎么做? 因为“资源类型Session没有实现java.lang.AutoCloseable”

我知道,我需要扩展 Session 并重写 AutoCloseable 方法,但是当我尝试这样做时,出现错误“Session 类型不能是 SessionDAO 的超类;超类必须是类”

更新

我已经编写了自己的 DAO 框架,但将为此使用 Spring

【问题讨论】:

标签: java hibernate session extends implements


【解决方案1】:

首先,您应该使用更可靠的会话/事务处理基础架构,就像 Spring 为您提供的那样。这样您就可以在多个 DAO 调用中使用相同的会话,并且事务边界由 @Transactional 注释显式设置。

如果这是你的测试项目,你可以像这样使用a simple utility

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;
}

你可以这样称呼它:

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();
        }
});

查看GitHub repository 了解更多类似的示例。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-22
    • 2012-03-17
    • 2012-06-09
    • 1970-01-01
    • 2015-02-19
    • 2012-04-10
    • 2019-08-06
    相关资源
    最近更新 更多