BaseHibernateDao的意思就是用泛型的方法实现一个基本的增删改查(CURD)方法,这样一些基本的单表操作直接继承这个类就可以实现了,例子如下:
public?class?BaseHibernateDAO?{
private?Session?session?=?null?;
private?Object?get(Class?clz?,?Serializable?id){
Object?ret?=?null?;
Session?session?=?HibernateSessionFactory.getSession();
try?{
ret?=?session.get(clz,?id);
}?catch?(HibernateException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}finally{
this.closeSession();
}
return?ret?;
}
protected?void?add(Object?item){
Transaction?tx?=?null?;
Session?session?=?HibernateSessionFactory.getSession();
try?{
tx?=?session.beginTransaction();
session.save(item);
tx.commit();
}?catch?(HibernateException?e)?{
//?TODO?Auto-generated?catch?block
if(tx?!=?null){
tx.rollback();
}
e.printStackTrace();
}finally{
closeSession();
}
}
public?void?delete(Class?clz?,?Serializable?id){
Transaction?tx?=?null?;
Session?session?=?HibernateSessionFactory.getSession();
try?{
tx?=?session.beginTransaction();
session.delete(this.get(clz,?id));
tx.commit();
}?catch?(HibernateException?e)?{
//?TODO?Auto-generated?catch?block
if(tx?!=?null){
tx.rollback();
}
e.printStackTrace();
}finally{
closeSession();
}
}
public?void?update(Object?item){
Transaction?tx?=?null?;
Session?session?=?HibernateSessionFactory.getSession();
try?{
tx?=?session.beginTransaction();
session.update(item);
tx.commit();
}?catch?(HibernateException?e)?{
//?TODO?Auto-generated?catch?block
if(tx?!=?null){
tx.rollback();
}
e.printStackTrace();
}finally{
closeSession();
}
}
public?List?search(Class?clazz?,?Object?condition){
List?results?=?null?;
try?{
Session?session?=?HibernateSessionFactory.getSession();
results?=?session.createCriteria(clazz).add(Example.create(condition)).list();
}?catch?(HibernateException?e)?{
//?TODO?Auto-generated?catch?block
e.printStackTrace();
}finally{
closeSession();
}
return?results;
}
protected?void?closeSession(){
this.session?=?null?;
HibernateSessionFactory.closeSession();
}
}
我不会~~~但还是要微笑~~~:)
用户登录
还没有账号?立即注册
用户注册
投稿取消
文章分类: |
|
还能输入300字
上传中....