---
title: "Hibernate 连接数据库的方法"
author: "1140566087"
date: "2013-09-26T12:52:30Z"
tags: ["DAO", "Hibernate"]
categories: ["编程语言"]
slug: "hibernate"
draft: false
lastmod: "2013-09-26T12:52:30Z"
id: 1947535
url: "https://sunzone.iteye.com/blog/1947535"
---

\[size=small]\[color=darkred]\[b]初级，最笨重的方法：\[/b]\[/color]\[/size] \[code="java"]package com.svse.dao; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.svse.entity.TDept; //部门数据处理 public class DeptDao\_1 { //全查询 ， public List getAll(){ List ar = new ArrayList(); //1、加载配置文件，连接数据库 Configuration config = new Configuration().configure(); //2、得到数据映射的工具：SessionFactory; SessionFactory sessionFactory = config.buildSessionFactory(); //3、得到动作处理工具Session，执行相应的动作； Session session = sessionFactory.openSession(); //4、使用Session工具执行动作; ar = session.createQuery("FROM TDept").list(); //5、关闭工具 session.close(); return ar; } //查询一个 public TDept getOne(int p\_id){ TDept dept = new TDept(); Configuration config = new Configuration().configure(); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); // 通过ID 获取到一个对象；TDept.class 使用到java的反射机制; dept = (TDept) session.get(TDept.class, new Integer(p\_id)); session.close(); return dept; } /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ /\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\** * 增、删、改 ：三种操作设计到数据的变化，则影响数据的安全性，所以需要使用事务以保证数据的 * 安全性； * * * * \*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*\*/ //增加 public void addDept(TDept dept){ Configuration config = new Configuration().configure(); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction ctx = session.beginTransaction(); //增加session.save(dept); session.save(dept); ctx.commit(); session.close(); } //修改 public void update(TDept dept){ Configuration config = new Configuration().configure(); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); //开启事务 Transaction ctx = session.beginTransaction(); //修改：update();方法 session.update(dept); //提交事务 ctx.commit(); session.close(); } //删除 public void delete(TDept dept){ Configuration config = new Configuration().configure(); SessionFactory sessionFactory = config.buildSessionFactory(); Session session = sessionFactory.openSession(); // 开启事务以保证数据的安全性； Transaction ctx = session.beginTransaction(); //动作：delete(); 操作 session.delete(dept); //提交事务 ctx.commit(); session.close(); } public static void main(String\[] args) { DeptDao\_1 dao = new DeptDao\_1(); System.out.println(dao.getAll().size()); } } \[/code] \[size=small]\[color=brown]\[b]中级：较为简化的连接方法：\[/b]\[/color]\[/size] \[code="java"]package com.svse.dao; import java.util.ArrayList; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.svse.entity.TUser; //使用封装类简化代码进行操作 public class UserDao1 { //定义基本属性字段 private static Configuration config = null; private static SessionFactory sessionFactory = null; private static Session session = null; private static Transaction ctx = null; //该内部类的特点：UserDao1这个实例化一次的时候自动的调用一次； static{ try{ config = new Configuration().configure(); sessionFactory = config.buildSessionFactory(); session = sessionFactory.openSession(); }catch(Exception ex){ ex.printStackTrace(); } } //增加 public void addUser(TUser user){ ctx = session.beginTransaction(); session.save(user); ctx.commit(); session.close(); } //修改 public void updateUser(TUser user){ ctx = session.beginTransaction(); session.update(user); ctx.commit(); session.close(); } //删除 public void delUser(TUser user){ ctx = session.beginTransaction(); session.delete(user); ctx.commit(); session.close(); } //全查询 public List getAll(){ List ar = new ArrayList(); ar = session.createQuery("FROM TUser").list(); session.close(); return ar; } //查询一个 public TUser getOne(int u\_id){ TUser user = new TUser(); user = (TUser) session.get(TUser.class, new Integer(u\_id)); session.close(); return user; } }\[/code] \[size=small]\[color=red]\[b]高级：最简单的方法，使用接口封装： 辅助类：\[/b]\[/color]\[/size] \[code="java"]package com.svse.util; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /\** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. \*/ public class HibernateSessionFactory { private static String CONFIG\_FILE\_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal threadLocal = new ThreadLocal(); 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 `SessionFactory` 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; } /\** * Rebuild hibernate session factory * \*/ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /\** * Close the single hibernate session instance. * * @throws HibernateException \*/ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /\** * return session factory * \*/ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /\** * return session factory * * session factory will be rebuilded in the next call \*/ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /\** * return hibernate configuration * \*/ public static Configuration getConfiguration() { return configuration; } }\[/code] \[size=small]\[color=red]\[b]定义接口规则：\[/b]\[/color]\[/size] \[code="java"]package com.svse.util; import org.hibernate.Session; //结果定义规则 public interface IHibernateSessionFactorySupport { //得到Session public Session getSession(); //开启事务 public void beginTransaction(); //提交事务 public void commitTransaction(); //关闭所有 public void closeAll(); }\[/code] \[size=small]\[color=red]\[b]接口实现，编写规则：\[/b]\[/color]\[/size] \[code="java"]package com.svse.util; import org.hibernate.Session; import org.hibernate.Transaction; public class HibernateSessionFactorySupportImpl implements IHibernateSessionFactorySupport { //定义事务的对象： private Transaction ctx = null; //开启事务 public void beginTransaction() { ctx = this.getSession().beginTransaction(); } //提交事务 public void commitTransaction() { try{ ctx.commit(); }catch(Exception ex){ ex.printStackTrace(); //事务回滚 if(ctx!=null){ ctx.rollback(); } }finally{ HibernateSessionFactory.closeSession(); } } //关闭所有:调用自动生类中定义方法 public void closeAll() { HibernateSessionFactory.closeSession(); } //得到Session public Session getSession() { //返回一个Session的对象 return HibernateSessionFactory.getSession(); } }\[/code] \[size=small]\[color=red]\[b] 具体数据获取，访问数据库得到数据：\[/b]\[/color]\[/size] \[code="java"] package com.svse.dao; import java.util.List; import com.svse.entity.TUser; import com.svse.util.HibernateSessionFactorySupportImpl; public class UserDao2 extends HibernateSessionFactorySupportImpl { //增加--涉及到数据的变化，需要使用事务 public void addUser(TUser user){ //第一步：开启事务 this.beginTransaction(); //第二步：执行动作 this.getSession().save(user); //第三步：提交事务，并关闭相关的工具 this.commitTransaction(); } //修改 public void updateUser(TUser user){ //第一步：涉及到数据的安全性，先开启事务； this.beginTransaction(); //第二步：获得Session对象并执行修改的动作； this.getSession().update(user); //第三步：提交事务，并关闭相关的工具； this.commitTransaction(); } //删除 public void delUser(int u\_id){ //1、开启事务 this.beginTransaction(); //2、执行动作 this.getSession().delete(this.getOne(u\_id)); //3、提交事务：并关闭相关的工具 this.commitTransaction(); } //查询一个 public TUser getOne(int u\_id){ //第一步：获取Session对象执行动作，得到集合对象获取数据； TUser user= (TUser) this.getSession().get(TUser.class, new Integer(u\_id)); //第二步：关闭Session工具； this.closeAll(); return user; } //全查询 public List getAll(){ List ar = this.getSession().createQuery("FROM TUser").list(); this.closeAll(); return ar; } public static void main(String\[] args) { UserDao2 dao = new UserDao2(); TUser user = new TUser(); user.setUId(1); user.setUName("小红aa"); user.setUPwd("123"); dao.updateUser(user); } }\[/code]