[英]How to properly start a SessionFactory?
I will need to be connected to my database in almost every page of my website. 我几乎需要在网站的每个页面上都连接到数据库。
My first page is a Login so I intent to start the SessionFactory
and keep it open for later use in other pages. 我的第一页是登录名,因此我打算启动
SessionFactory
并将其保持打开状态,以便以后在其他页面中使用。
My question is: How can I declare the variable global so I can use it everywhere in my other classes? 我的问题是:如何声明全局变量,以便可以在其他类中的任何地方使用它?
public SessionFactory StartDatabaseConnection() {
SessionFactory factory;
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
return factory;
}
How do I use it here now?? 我现在如何在这里使用它?
factory doesn't exist in context
private Integer addGeneralSetup(GeneralSetup generalSetup) {
Session session = factory.openSession();
Transaction tx = null;
Integer generalSetupID = null;
try{
tx = session.beginTransaction();
generalSetupID = (Integer) session.save(generalSetup);
tx.commit();
}catch (HibernateException e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
return generalSetupID;
}
The best practice in my opinion is to use singleton spring bean and inject the dependency whenever required. 我认为最佳实践是使用单例spring bean,并在需要时注入依赖项。
Spring provides 2 ways to achieve this: 1. Spring has inbuilt templates ready to be used For example: Spring提供了两种方法来实现此目的:1. Spring具有内置模板可供使用,例如:
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<bean id="customBean" class="com.learn.custom.CustomBean" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.