Hibernate的命名策略使用引起的Sessionfactory创建问题
SessionFactory是一个重量级组件,一个数据源应该只创建一个SessionFactory对象,而我需要使用Namingstrategy,方式如下:
Configuration cfg = new Configuration();
MyNamingStrategy m = new MyNamingStrategy(tableName);
cfg.setNamingStrategy(m);
sessionFactory = cfg.configure().buildSessionFactory();
Session session = sessionFactory.openSession();
其中,tableName是一个字符串变量,并不是一个固定不变的字符串。但这样一来,每次开启一个session就需要创建一个SessionFactory对象,这将大大占用资源,请问如何在使用命名策略的情况下不用开启大量的SessionFactory对象?
------解决方案--------------------SessionFactory 果断使用静态 。
如果是多数据库,用静态 hash 里面加 静态 session faction
------解决方案-------------------- /**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration = new Configuration();
private static org.hibernate.SessionFactory sessionFactory;
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err .println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the <code>SessionFactory</code> if needed.
*
* @return Session
* @throws
HibernateException */
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
这个是自动生成 hibernate 数据访问类,你看session = (sessionFactory != null) ? sessionFactory.openSession()
这句,很明显一级缓存,映射那块,只需要加载一次,如果你没有完整的数据访问类,可以用myeclipse 自动生成。
------解决方案--------------------这个问题,我也遇到过,最后果断换方法