用户登录
用户注册

分享至

hibernate 4 通用curd

  • 作者: 胖妞要瘦
  • 来源: 51数据库
  • 2021-01-03
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();
}
}



  我不会~~~但还是要微笑~~~:)
软件
前端设计
程序设计
Java相关