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);
- }
- }
本文介绍了一个使用Hibernate框架实现的对象关系映射(ORM)工具类,包括会话工厂创建、获取当前会话、关闭会话等基本操作,并提供了加载、保存、更新、删除及查询对象的方法。
316

被折叠的 条评论
为什么被折叠?



