废话不多说,直接搞张图出来,大家看看就明白了、。。。。
晕这边图还不能贴上来
放到文件里吧
下面是代码,没代码怎么行........................................................
HibernateUtil.java
package org.zzx.hibernate.transaction;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
@SuppressWarnings("unchecked")
public class ThreadLocalHibernate {
private static SessionFactory sessionFactory;
static {
sessionFactory=new Configuration().configure().buildSessionFactory();
}
private static Session getSessionHelp(){
return sessionFactory.openSession();
}
private static ThreadLocal threadSession=new ThreadLocal();
private static Session session;
public static Session getSession(){
session=(Session)threadSession.get();
if(session==null){
session=getSessionHelp();
threadSession.set(session);
}
return session;
}
public static void close(){
if(session!=null){
session.close();
threadSession.set(null);
}
}
}
有了HibernateUtil还要有filter啊,不急,贴出来。。。。。
package org.zzx.hibernate.transaction;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TransactionInView implements Filter {
private Session hibernateSession;
private Transaction transaction;
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
hibernateSession = ThreadLocalHibernate.getSession();
transaction = hibernateSession.getTransaction();
try {
transaction.begin();
chain.doFilter(request, response);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
ThreadLocalHibernate.close();
}
}
public void init(FilterConfig filterConfig) throws ServletException {
}
}
filter在web.xml是这样配置的
<filter>
<filter-name>transaction</filter-name>
<filterclass>
org.zzx.hibernate.transaction.TransactionInView
</filter-class>
</filter>
<filter-mapping>
<filter-name>transaction</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
上面的url-pattern是对所有的请求都进行过滤,这样效率会下降的,建议换成你要过滤的,也就是你要持久数据的操作时
才让这个filter过滤
好了基本的代码就这么多了,,剩下的,只要在业务层持久或查找数据就Ok了。这里的代码只是对session的事务这一块
做了简单的示例,不过用这种方法对session事务管理,在性能上是有风险的。这个session的事务在整个请求和回复的过程中都开着,如果用户查的数据比较大并且用户的网络不是很好的话,则Hibernate会有一级缓存会缓存数据,对服务器的内存是一种挑战,特别是好多用户并发时。
- 大小: 122.5 KB
分享到:
评论