[英]What is a good design pattern for DB manager that provides Session object in Hibernate?
I'm developing a class that provides a session to any consumer. 我正在开发一个为任何消费者提供会话的课程。 So, the class is responsible of getting a SessionFactory and opening up a session and passing it whenever needed.
因此,该类负责获取SessionFactory并打开会话并在需要时传递它。
So, What is a better design? 那么,什么是更好的设计? Static method in a class like this?
像这样的类中的静态方法?
public class DbStatIo {
private static SessionFactory factory=null;
public static Session getSessionForStatDb(){
if (factory==null){
SessionFactory factory=new Configuration()
.configure(FilesManager.getSenseiConfigForStatDb())
.buildSessionFactory();
}
return factory.openSession();
}
}
or just a local public function? 还是只是当地的公共职能? Or something else?
或者是其他东西?
The creation of a SessionFactory
instance is a very expensive operation due to the amount of information it holds (as shown here ); 一个的创建
SessionFactory
实例是非常昂贵的操作由于信息它所占用的量(如所示在这里 ); since it is thread-safe, having a single instance (as a singleton) or keeping a static reference should be sufficient. 因为它是线程安全的,具有单个实例(作为单例)或保持静态引用应该就足够了。
However, using it as a singleton might give you better, more flexible control over the lifetime of the object than storing it as a field in static class. 但是,将它作为单例使用可能会比在静态类中将其作为字段存储更好,更灵活地控制对象的生命周期。 You can have a dependency on your data access objects to a
IDatabaseService
, exposing a method getSession
, implemented by a single instance of HibernateService
. 您可以依赖于
IDatabaseService
数据访问对象,公开由单个HibernateService
实例实现的方法getSession
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.