gpt4 book ai didi

java - Session.close() 对 Spring openSessionInView 有影响吗?

转载 作者:行者123 更新时间:2023-11-29 06:12:55 24 4
gpt4 key购买 nike

我在 web.xml 中有 openSessionInView 过滤器。

<filter>
<filter-name>openSessionInView</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
</filter>

并且我已将 HibernateDaoSupport 的 allowCreate 属性设置为 true。现在对于每个数据库操作,如果我通过 getSession 获取 Session 并在交易后关闭 Session,例如:

public List<User> getAllUsers() {
Session session = getSession();
session.enableFetchProfile("USER-ROLE-PROFILE");
Transaction transaction = session.beginTransaction();
DetachedCriteria criteria = DetachedCriteria.forClass(User.class);
List<User> users = criteria.getExecutableCriteria(session).list();
transaction.commit();
session.disableFetchProfile("USER-ROLE-PROFILE");
session.close();
return users;
}

那么这个 Session 关闭是否会在 openSessionInView 中产生任何问题?

另一个问题:这是进行各种 hibernate 操作的好方法吗?在上面的代码中,实体 User 有一个获取配置文件。

感谢和问候。

最佳答案

如果 getAllUsers() 是请求生命周期中要做的最后一件事,这种方法是可以接受的。但是如果你想做更多的数据库操作,那么你必须打开一个新的 session ,因为你已经关闭了它。此外,如果您不关闭 session ,它将被过滤器关闭:

    public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {

...// sf is SessionFactory

sf.getCurrentSession().beginTransaction();

// Call the next filter (continue request processing)
chain.doFilter(request, response);

sf.getCurrentSession().getTransaction().commit();

...
}

关于java - Session.close() 对 Spring openSessionInView 有影响吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6169101/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com