![](/img/trans.png)
[英]Java error "The resource type Connection does not implement java.lang.AutoCloseable" in the try-catch connection
[英]Hibernate “The resource type Session does not implement java.lang.AutoCloseable”
我想用建築
import org.hibernate.Session;
...
try (Session session){
}
我怎樣才能做到這一點? 因為“資源類型Session沒有實現java.lang.AutoCloseable”
我知道,我需要擴展Session並覆蓋AutoCloseable方法,但是當我嘗試這樣做時,會出現錯誤“類型Session不能是SessionDAO的超類;超類必須是一個類”
更新
我已經編寫了自己的DAO框架,但是會使用Spring
首先,您應該使用更加可靠的會話/事務處理基礎架構,就像Spring為您提供的那樣。 這樣,您可以跨多個DAO調用使用相同會話,並且事務邊界由@Transactional注釋顯式設置。
如果這是您的測試項目,您可以使用像這樣的簡單實用程序 :
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存儲庫以獲取更多此類示例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.