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();
}
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。