java 代码
- public class HibernateSessionFactory {
- private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml" ;
- private static final ThreadLocal threadLocal = new ThreadLocal();
- private static final Configuration cfg = new Configuration();
- private static org.hibernate.SessionFactory sessionFactory;
- public static Session currentSession() throws HibernateException {
- Session session = (Session) threadLocal.get();
- if (session == null || !session.isOpen()) {
- if (sessionFactory == null ) {
- try {
- cfg.configure(CONFIG_FILE_LOCATION);
- sessionFactory = cfg.buildSessionFactory();
- } catch (Exception e) {
- System.err.println( "%%%% Error Creating SessionFactory %%%%" );
- e.printStackTrace();
- }
- }
- session = (sessionFactory != null ) ? sessionFactory.openSession(): null ;
- threadLocal.set(session);
- }
- return session;
- }
- public static void closeSession() throws HibernateException {
- Session session = (Session) threadLocal.get();
- threadLocal.set( null );
- if (session != null ) {
- session.close();
- }
- }
- private HibernateSessionFactory() {
- }
- }
java 代码
- public class DAOTool {
- public Object load (Object object,Integer id) {
- Session session = HibernateSessionFactory.currentSession();
- return session.load(object. class , id);
- }
- public Object get (Object object ,Integer id) {
- Session session = HibernateSessionFactory.currentSession();
- return session.get(object. class , id);
- }
- public List find(String hql) {
- Session session = HibernateSessionFactory.currentSession();
- return session.createQuery(hql).list();
- }
- public Serializable save (Object obj) {
- Session session = HibernateSessionFactory.currentSession();
- return session.save(obj);
- }
- public void update(Object obj) {
- Session session = HibernateSessionFactory.currentSession();
- session.update(obj);
- }
- public void update(String hql, Object obj) {
- Session session = HibernateSessionFactory.currentSession();
- session.update(hql, obj);
- }
- public void delete(Object obj) {
- Session session = HibernateSessionFactory.currentSession();
- session.delete(obj);
- }
- public void delete(String hql, Object obj) {
- Session session = HibernateSessionFactory.currentSession();
- session.delete(hql, obj);
- }
- }