open session in view 简称 OSIV 模式
在Hibernate中能更好的应用Hibernate的性能,会在Hibernate中使用延迟加载的性能,在读取一个持久化对象的时候,可能这个对象会关联到另一个对象,使用延迟加载之后,读取持久化对象,而那些所被关联的持久化对象,如果当时不需要被读取,这些所被关联的持久化对象时不会被读取的,只有能到这些被关联的持久化对象,在需要读取的时候再去通过session对象来对底层的数据库进行读取,利用这些延迟加载,可以提高Hibernate的性能,但是也会带来一些问题,容易引出一些违例
例如
Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize proxy - no session
解决上述问题有2个思路
1.在Hibernate当中延迟加载给禁止,但性能会造成较大的损失
2.延长session的生命周期,把所有要读取的数据都读取完毕后(包括持久化对象所关联的数据)在关闭session.
//假设以下代码在控制层执行
Session session =HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Testbook tb =(Testbook)session.load(Testbook.class,new Integer(1));
//....
//..接着,以下代码在表示层执行
System.out.println(tb.getEmail());
System.out.println(tb.getTitle());
tx.commit();//在所有事情都做完后再关闭session
使用Servlet过滤器实现OSIV模式
当用户向一个jsp页面或者servlet发出请求的时候开启session对象,在jsp页面或者servlet执行之后再关闭session对象。
泛型DAO模式
使用dao设计模式可以实现不同持久化框架的切换,使用泛型可以编写一个泛型的dao接口,一个泛型的dao接口的实现类
在这个接口和实现类,把通用的接口和实现类都实现后,在把具体的dao接口和实现类,不用重复的去定义这些crud的基本方法 crud: Create(创建)、Read(读取)、Update(更新)和Delete(删除)直接继承泛型的dao接口,继承泛型的dao接口的实现类
demo:
import java.io.Serializable;
import java.util.List;
public interface GenericDao<T,PK extends Serializable> {
public T findById(PK id);
public List<T> findAll();
public T save(T entity);
public void update(T entity);
public void delete(T entity);
}
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import com.v512.guestbook.dao.GenericDao;
import com.v512.util.HibernateSessionFactoryUtil;
public abstract class GenericDaoHibernate<T, PK extends Serializable> implements GenericDao<T, PK> {
private Class<T> clazz;
public GenericDaoHibernate() {
clazz = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass())
.getActualTypeArguments()[0];
}
public T findById(PK id) {
Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
return (T) session.get(clazz, id);
}
public List<T> findAll() {
Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
Query query = session.createQuery("from " + clazz.getName());
return query.list();
}
public T save(T entity) {
Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
session.save(entity);
return entity;
}
public void update(T entity) {
Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
session.update(entity);
}
public void delete(T entity) {
Session session = HibernateSessionFactoryUtil.getSessionFactory().getCurrentSession();
session.delete(entity);
}
}
本文介绍了opensessioninview(OSIV)模式如何帮助提升Hibernate框架的性能,特别是延迟加载特性带来的优势及其潜在问题。文中还提供了通过延长session生命周期来解决LazyInitializationException异常的方法,并展示了如何使用泛型DAO模式简化不同持久化框架间的切换。
1054

被折叠的 条评论
为什么被折叠?



