[英]Hibernate “The resource type Session does not implement java.lang.AutoCloseable”
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"
因为“资源类型Session没有实现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" 我知道,我需要扩展Session并覆盖AutoCloseable方法,但是当我尝试这样做时,会出现错误“类型Session不能是SessionDAO的超类;超类必须是一个类”
Update 更新
I've wrote my own DAO framework, but will be use Spring for that 我已经编写了自己的DAO框架,但是会使用Spring
First, you should use a much more solid session/transaction handling infrastructure, like Spring offers you. 首先,您应该使用更加可靠的会话/事务处理基础架构,就像Spring为您提供的那样。 This way you can use the Same Session across multiple DAO calls and the transaction boundary is explicitly set by the @Transactional annotation.
这样,您可以跨多个DAO调用使用相同会话,并且事务边界由@Transactional注释显式设置。
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. 检查此GitHub存储库以获取更多此类示例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.