代码改变世界

【hibernate】HibernateUtil和Hibernate的DAO

2012-12-21 21:49  Loull  阅读(579)  评论(0)    收藏  举报

HibernateUtil

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    private static final ThreadLocal m_session = new ThreadLocal();  
    
    static {
        try {
            Configuration config = new Configuration();
            config.addFile("src\\main\\resources\\hibernate.cfg.xml").configure();
            sessionFactory = config.buildSessionFactory();
        } catch (HibernateException ex) {
            throw new RuntimeException("创建SessionFactory失败: " + ex.getMessage(), ex);  
        }
    }
    
    public static Session currentSession() throws HibernateException {  
        Session s = (Session) m_session.get();  
        if (s == null) {  
            s = sessionFactory.openSession();  
            m_session.set(s);  
        }  
        return s;  
    }  
      
    public static void closeSession() throws HibernateException {  
        Session s = (Session) m_session.get();  
        m_session.set(null);  
        if (s != null)  
            s.close();  
    }  
}

Hibernate的DAO

import java.util.List;

import org.ccnt.health.znserver.entry.NormalIll;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class NormalIllDAO {
    
    public void insertNormal(NormalIll nill){
        Session session = HibernateUtil.currentSession();
        Transaction tx = session.beginTransaction();
        session.save(nill);
        tx.commit();
        HibernateUtil.closeSession();
    }
    
    public void insertNormalList(List<NormalIll> li){
        for (NormalIll e : li){
            insertNormal(e);
        }
    }
    
    public List<NormalIll> getAll(){
        Session session = HibernateUtil.currentSession();
        String hql = "from NormalIll";
        Query query = session.createQuery(hql);
        List<NormalIll> list = query.list();
        return list;
    }
    
    public NormalIll getByName(String name){
        Session session = HibernateUtil.currentSession();
        String hql = "from NormalIll n where n.name = " + name;
        Query query = session.createQuery(hql);
        return (NormalIll)query.list().get(0);
    }
    
    public NormalIll getById(int id){
        Session session = HibernateUtil.currentSession();
        String hql = "from NormalIll n where n.id = " + id;
        Query query = session.createQuery(hql);
        return (NormalIll)query.list().get(0);
    }
}