hibernatefactory.java
来自「hibernate spring模板执行代码例子下载」· Java 代码 · 共 85 行
JAVA
85 行
import org.hibernate.*;
import org.hibernate.cfg.Configuration;
import org.apache.commons.logging.*;
public class HibernateFactory {
private static SessionFactory sessionFactory;
private static Log log = LogFactory.getLog(HibernateFactory.class);
/**
* Constructs a new Singleton SessionFactory
* @return
* @throws HibernateException
*/
public static SessionFactory buildSessionFactory() throws HibernateException {
if (sessionFactory != null) {
closeFactory();
}
return configureSessionFactory();
}
/**
* Builds a SessionFactory, if it hasn't been already.
*/
public static SessionFactory buildIfNeeded() throws DataAccessLayerException{
if (sessionFactory != null) {
return sessionFactory;
}
try {
return configureSessionFactory();
} catch (HibernateException e) {
throw new DataAccessLayerException(e);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
public static Session openSession() throws HibernateException {
buildIfNeeded();
return sessionFactory.openSession();
}
public static void closeFactory() {
if (sessionFactory != null) {
try {
sessionFactory.close();
} catch (HibernateException ignored) {
log.error("Couldn't close SessionFactory", ignored);
}
}
}
public static void close(Session session) {
if (session != null) {
try {
session.close();
} catch (HibernateException ignored) {
log.error("Couldn't close Session", ignored);
}
}
}
public static void rollback(Transaction tx) {
try {
if (tx != null) {
tx.rollback();
}
} catch (HibernateException ignored) {
log.error("Couldn't rollback Transaction", ignored);
}
}
/**
*
* @return
* @throws HibernateException
*/
private static SessionFactory configureSessionFactory() throws HibernateException {
Configuration configuration = new Configuration();
configuration.configure();
sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?