package com.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;

import com.tools.HibernateSessionFactory;

public class BaseHibernateDAO {

/**
 * 添加数据
 * @param object
 */
public void add(Object object){
    Transaction tran = null;
    Session session = HibernateSessionFactory.getSession();

    try {
        tran = session.beginTransaction();
        session.save(object);
        tran.commit();
    } catch (Exception e) {
        if (tran!=null) {
            //
            tran.rollback();
        }
    }finally{
        session.close();
    }
}

/**
 * 加载(得到)数据
 * @param cla
 * @param id
 * @return
 */
public Object get(Class cla, Serializable id){
    Object object = null;
    Session session = HibernateSessionFactory.getSession();

    try {
        object = session.get(cla, id);
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        session.close();
    }
    return object;
}

/**
 * 搜索数据
 * @param cla
 * @param condition
 * @return
 */
public List search(Class cla, Object condition){
    Session session = null;
    List list = null;

    try {
        System.out.println("step 4 : Start Session..");
        session = HibernateSessionFactory.getSession();

        Criteria cr = session.createCriteria(cla);
        cr.add(Example.create(condition));  
        System.out.println("Criteria is: " + cr);
        list = cr.list();
        System.out.println("last step: list size: " + list.size());
    } catch (Exception e) {
        // TODO: handle exception
    }finally{
        session.close();
    }

    return list;
}

/**
 * 删除数据
 * @param object
 */
public void delete(Object object){
    Transaction tran = null;
    Session session = HibernateSessionFactory.getSession();

    try {
        tran = session.beginTransaction();
        session.delete(object);
        tran.commit();

    } catch (Exception e) {
        if (tran!=null) {
            tran.rollback();
        }
        e.printStackTrace();
    }finally{
        session.close();
    }
}

/**
 * 修改数据
 * @param object
 */
public void update(Object object){
    Transaction tran = null;
    Session session = HibernateSessionFactory.getSession();

    try {
        tran = session.beginTransaction();
        session.update(object);
        tran.commit();
    } catch (Exception e) {
        if (tran!=null) {
            tran.rollback();
        }
        e.printStackTrace();
    }finally{
        session.close();
    }
}

}


yizheng
301 声望27 粉丝

一蓑烟雨任平生


引用和评论

0 条评论