简体   繁体   English

通过servlet中的Hibernate进行数据库连接

[英]Database connection via Hibernate in servlets

What is the best place in servlet for Hibernate code that returns HibernateSessionFactory ? 返回HibernateSessionFactory的Hibernate代码在servlet中最好的地方是什么?

I saw many examples: ones put db connection in service methods. 我看到很多例子:将db连接放在服务方法中。 Others - use smth like HibernateUtil (Singleton) that returns HibernateSessionFactory. Others - 使用类似HibernateUtil(Singleton)的smth返回HibernateSessionFactory。

I don't know is it safe to use HibernateUtil in multithreaded Servlets ? 我不知道在多线程Servlet中使用HibernateUtil是否安全?

Usually, you should use an MVC framework in favor of Servlets directly, but that's not your question, and I'm going to assume you have a good reason to be implementing your own Servlets. 通常,您应该直接使用MVC框架来支持Servlet,但这不是您的问题,我将假设您有充分的理由来实现自己的Servlet。 On to the answer... 回答......

Per this - https://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html : 按此 - https://www.hibernate.org/hib_docs/v3/api/org/hibernate/SessionFactory.html

Implementors must be threadsafe. 实现者必须是线程安全的。

and

SessionFactorys are immutable. SessionFactorys是不可变的。 The behaviour of a SessionFactory is controlled by properties supplied at configuration time. SessionFactory的行为由配置时提供的属性控制。 These properties are defined on Environment . 这些属性在Environment上定义。

So it's OK to share an instance of SessionFactory s. 所以共享SessionFactory的实例是可以的。

In fact, from my experience, your HibernateUtil approach is the better approach, as SessionFactory creation can be very expensive. 事实上,根据我的经验,您的HibernateUtil方法是更好的方法,因为SessionFactory创建可能非常昂贵。

在视图模式中使用Open Session (请参阅过滤器实现)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM