Hibernate 框架作为一个优秀的持久化层轻量级框架具有很大优势,通过一个通用的DAO封装,我们将 Hibernate 相关的代码隐藏起来。
1.利用 MyEclipse 引入 Hibernate 框架 并自动创建 HibernateSessionFactory
2.封装 Hibernate 的通用DAO类
package cn.net.royakon.dao;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Example;
/**
* 使用 HibernateSessionFactory 创建的通用DAO
* 本类为 抽象类 业务DAO 均继承此类
* 得到记录集合的操作仅支持精确过滤
* 模糊查询需要业务DAO自行编写
* @author RoyAkon
*/
abstract public class BaseHibernateDAO {
/**
* 得到Session
* @return
*/
public Session getSession() {
return HibernateSessionFactory.getSession();
}
/**
* 关闭Session
*/
public void closeSession() {
HibernateSessionFactory.closeSession();
}
/**
* 实现增加数据库记录的操作
* @param item
*/
protected void add(Object item){
try {
Transaction tx = getSession().beginTransaction();
getSession().save(item);
tx.commit();
} catch (RuntimeException re) {
throw re;
} finally{
this.closeSession();
}
}
/**
* 实现根据主键取得某条记录的操作
* @param id
* @param clazz
* @return
*/
protected Object get(java.io.Serializable id,Class clazz){
try {
Object item = getSession().get(clazz, id);
return item;
} catch (RuntimeException re) {
throw re;
} finally{
this.closeSession();
}
}
/**
* 实现根据主键删除记录的操作
* @param id
* @param clazz
*/
protected void del(java.io.Serializable id,Class clazz){
Transaction tx = null;
try {
tx = getSession().beginTransaction();
getSession().delete(this.get(id, clazz));
tx.commit();
} catch (RuntimeException re) {
tx.rollback();
throw re;
} finally{
this.closeSession();
}
}
/**
* 实现更新记录的操作
* @param item
*/
protected void update(Object item){
try {
Transaction tx = getSession().beginTransaction();
getSession().update(item);
tx.commit();
} catch (RuntimeException re) {
throw re;
} finally{
this.closeSession();
}
}
/**
* 实现根据条件精确过滤取得结果集的操作
* @param condition
* @param clazz
* @return
*/
protected List search(Object condition,Class clazz){
try {
List results = getSession()
.createCriteria(clazz)
.add(Example.create(condition))
.list();
return results;
} catch (RuntimeException re) {
throw re;
} finally{
this.closeSession();
}
}
}
3.业务 DAO 的编写
package cn.net.royakon.dao;
import cn.net.royakon.entity.User;
/**
* 业务DAO 继承自 BaseHibernateDAO
* @author RoyAkon
*
*/
public class User extends BaseHibernateDAO {
/**
* 添加用户
* @param user
*/
public void addUser(User user) {
super.add(user);
}
}
大家可以看到,在具体到业务实现时,用户业务DAO的编写实现完全隐藏 Hibernate 代码。DAO代码是不是清爽无比?
Categories: 网页编程