2 回答

TA貢獻(xiàn)1827條經(jīng)驗 獲得超8個贊
當(dāng)您使用以下方法管理器加載數(shù)據(jù)時,問題開始。
public <T> List<T> loadAllData(Class<T> type)
{
// New session was opened here
Session session = sessionFactory.openSession();
session.beginTransaction();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<T> criteria = builder.createQuery(type);
criteria.from(type);
List<T> data = session.createQuery(criteria).getResultList();
session.getTransaction().commit();
session.close();
//session is close here
return data;
}
因此,當(dāng)您加載數(shù)據(jù)時,休眠框架將僅加載用戶對象。由于您已選擇在模型類中使用延遲加載,因此只有在您嘗試訪問列表時才會加載應(yīng)用程序值。由于您已經(jīng)關(guān)閉了會話,因此框架無法再獲取應(yīng)用程序列表,從而導(dǎo)致延遲加載異常。
listOfApplications = managerHibernate.loadAllData(Application.class);
//loading user data and close the session associated with it
listOfUsers = managerHibernate.loadAllData(User.class);
User user = null;
Application app = null;
for(Application index: listOfApplications)
{
if(index.getApplicationName().equals(applicationName))
{
okApp = 1;
app = index;
}
}
for(User index: listOfUsers)
{
if(index.getUserUserName().equals(userUserName))
{
okUser = 1;
user = index;
}
}
if(okUser == 0 || okApp == 0)
return false;
else
{
// when you run this line the hibernate framework will try to retrieve the application data.Since you have the closed session lazy load exception occurs
user.getListOfApplications().add(app);
return true;
}
解決此問題的方法
1)嘗試保持會話打開狀態(tài),以便您的框架可以獲取應(yīng)用程序數(shù)據(jù)
2)在模型pojo類中將延遲加載更改為預(yù)先加載(因為您正在使用多對多關(guān)系,因此不建議以這種方式使用)

TA貢獻(xiàn)1860條經(jīng)驗 獲得超9個贊
由于沒有用于獲取用戶中應(yīng)用程序的惰性列表的事務(wù),因此您需要先獲取它。為了做到這一點,你可以改變loadAllData,如下所示:
public interface CriteriaSpec
{
public void joinFetch(CriteriaBuilder builder, CriteriaQuery criteria, Root root);
}
public <T> List<T> loadAllData(Class<T> type, Optional<CriteriaSpec> spec)
{
Session session = sessionFactory.openSession();
session.beginTransaction();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<T> criteria = builder.createQuery(type);
Root root = criteria.from(type);
if(spec.isPresent())
spec.joinFetch(builder, criteria, root);
List<T> data = session.createQuery(criteria).getResultList();
session.getTransaction().commit();
session.close();
return data;
}
然后使用它:
managerHibernate.loadAllData(Application.class, Optional.empty());
listOfUsers = managerHibernate.loadAllData(User.class, (rootEntity, query,
criteriaBuilder) -> {
rootEntity.fetch("listOfApplications", JoinType.Left_OUTER_JOIN);
});
添加回答
舉報