休止状態での遅延初期化の問題を解決するために、次のアプローチを使用しています。うまくいくかどうか教えてください。いくつかの理由により、強制的に永続化レイヤーにトランザクションを実装する必要があります。
public class CourseDAO {
Session session = null;
public CourseDAO() {
session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public Course findByID(int cid) {
Course crc = null;
Transaction tx = null;
try {
tx = session.beginTransaction();
Query q = session.createQuery(
"from Course as course where course.cid = "+cid+" "
);
crc = (Course) q.uniqueResult();
//note that i am not commiting my transcation here.
//Because If i do that i will not be able to do lazy fetch
}
catch (HibernateException e) {
e.printStackTrace();
tx.rollback();
throw new DataAccessLayerException(e);
}
finally {
return crc;
}
}
}
フィルターでは、次のコードを使用しています
session = HibernateUtil.getSessionFactory().getCurrentSession();
if(session.isOpen())
session.getTransaction().commit();
このアプローチは正しいですか?問題が発生する可能性があります。