其实对Hibernate进行分析后可以发现,这个Hibernate对于对象的增加。删除,更新是差不多的,所以可以把他们整合到一个工具类中去。还有就是,因为查询是很复杂的,所以对于数据库的查询,就有相对应的接口,类似于JDBC中的PreparedStatemented这个类。下面我们先看一下工具类的增强
- package com.bird.hibernate.test;
- import org.hibernate.HibernateException;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- @SuppressWarnings("deprecation")
- public final class Hibernateutils {
- private static SessionFactory sf;
- private Hibernateutils(){}
- static{
- Configuration cfg = new Configuration();
- cfg.configure();
- sf = cfg.buildSessionFactory();
- }
- public static SessionFactory getSessionFactory() {
- return sf;
- }
- public static Session getSession(){
- return sf.openSession();
- }
- public static void add(Object entity){
- Session s = null;
- Transaction ts = null;
- try {
- s = sf.openSession();
- ts = s.beginTransaction();
- s.save(entity);
- ts.commit();
- } catch (HibernateException e) {
- if (ts != null)
- ts.rollback();
- throw e;
- } finally {
- if (s != null)
- s.close();
- }
- }
- public static void update(Object entity){
- Session s = null;
- Transaction ts = null;
- try {
- s = sf.openSession();
- ts = s.beginTransaction();
- s.update(entity);
- ts.commit();
- } catch (HibernateException e) {
- if (ts != null)
- ts.rollback();
- throw e;
- } finally {
- if (s != null)
- s.close();
- }
- }
- public static void delete(Object entity){
- Session s = null;
- Transaction ts = null;
- try {
- s = sf.openSession();
- ts = s.beginTransaction();
- s.delete(entity);
- ts.commit();
- } catch (HibernateException e) {
- if (ts != null)
- ts.rollback();
- throw e;
- } finally {
- if (s != null)
- s.close();
- }
- }
- }
