此篇接上篇(java架构搭建(一))继续 http://blog.csdn.net/lushuaiyin/article/details/8588203
到此按照步骤应该测试ssh的整合是否可用
为什么要用HibernateTemplate?因为它已经帮我们封装好了很多方法(在spring中)。我们不必直接调用sessionFactory,再调用事务transAction,再调用session...
我们使用hibernate无非就是操作数据库,就是增删改查。这里封装好了,我们直接用就很方便了。在此我再进一步封装,以便于我们自己理解和使用,
或者简化它,或者完善它。对HibernateTemplate的封装,我们并不直接继承org.springframework.orm.hibernate3.HibernateTemplate,
而是继承org.springframework.orm.hibernate3.support.HibernateDaoSupport。为什么呢?我们看看源码:
/*jadclipse*/// Decompiled by Jad v1.5.8g. Copyright 2001 Pavel Kouznetsov. package org.springframework.orm.hibernate3.support; import org.hibernate.*; import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.dao.support.DaoSupport; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.SessionFactoryUtils; public abstract class HibernateDaoSupport extends DaoSupport { public HibernateDaoSupport() { } public final void setSessionFactory(SessionFactory sessionFactory) { if(hibernateTemplate == null || sessionFactory != hibernateTemplate.getSessionFactory()) hibernateTemplate = createHibernateTemplate(sessionFactory); } protected HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) { return new HibernateTemplate(sessionFactory); } public final SessionFactory getSessionFactory() { return hibernateTemplate == null ? null : hibernateTemplate.getSessionFactory(); } public final void setHibernateTemplate(HibernateTemplate hibernateTemplate) { this.hibernateTemplate = hibernateTemplate; } public final HibernateTemplate getHibernateTemplate() { return hibernateTemplate; } protected final void checkDaoConfig() { if(hibernateTemplate == null) throw new IllegalArgumentException("'sessionFactory' or 'hibernateTemplate' is required"); else return; } protected final Session getSession() throws DataAccessResourceFailureException, IllegalStateException { return getSession(hibernateTemplate.isAllowCreate()); } protected final Session getSession(boolean allowCreate) throws DataAccessResourceFailureException, IllegalStateException { return allowCreate ? SessionFactoryUtils.getSession(getSessionFactory(), hibernateTemplate.getEntityInterceptor(), hibernateTemplate.getJdbcExceptionTranslator()) : SessionFactoryUtils.getSession(getSessionFactory(), false); } protected final DataAccessException convertHibernateAccessException(HibernateException ex) { return hibernateTemplate.convertHibernateAccessException(ex); } protected final void releaseSession(Session session) { SessionFactoryUtils.releaseSession(session, getSessionFactory()); } private HibernateTemplate hibernateTemplate; } /* DECOMPILATION REPORT Decompiled from: D:\ChinaDevelopmentBankJBPM\workSpace\frame\webapp\WEB-INF\lib\spring-orm-3.0.3.RELEASE.jar Total time: 139 ms Jad reported messages/errors: Exit status: 0 Caught exceptions: */
public final void setHibernateTemplate(HibernateTemplate hibernateTemplate)是为了注入hibernateTemplate;
我们在applicationContext.xml中配置好后,就可以注入。要使用这些对象只要用get方法即可获取到。
而org.springframework.orm.hibernate3.HibernateTemplate类主要实现了数据库的操作,里面的方法很多。
比如public void saveOrUpdate(final Object entity);public Serializable save(final Object entity);
public void delete(Object entity);其中有个方法比较重要,因为和事务有关:
public Object execute(HibernateCallback action) throws DataAccessException { return doExecute(action, false, false); }
package org.base; import java.io.Serializable; import java.sql.SQLException; import java.util.List; import org.hibernate.HibernateException; import org.hibernate.Query; import org.hibernate.SQLQuery; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.dao.DataAccessException; import org.springframework.orm.hibernate3.HibernateCallback; import org.springframework.orm.hibernate3.HibernateTemplate; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; public abstract class MyHibernateDao extends HibernateDaoSupport { protected final HibernateTemplate createHibernateTemplate(SessionFactory sessionFactory) { return new HibernateTemplate(sessionFactory); } /////////////////////以下是对原生SQL语句的封装/////////////////////////// //执行insert,update,delete语句 public void executeSql(final String sql) { this.getHibernateTemplate().execute( new HibernateCallback<Object>(){ public Object doInHibernate(Session session) throws HibernateException { session.createSQLQuery(sql).executeUpdate(); return null; } } ); } //执行select语句 public List querySql(final String sql) { return (List) this.getHibernateTemplate().execute( new HibernateCallback<Object>() { public Object doInHibernate(Session session) throws HibernateException { try { SQLQuery query = session.createSQLQuery(sql); return query.list(); } catch (Exception e) { return null; } } } ); } /////////////////////以下是对HQL语句的封装/////////////////////////// //执行insert,update,delete语句 public int executeHql(final String hql) throws DataAccessException { return ((Integer)this.getHibernateTemplate().execute( new HibernateCallback<Object>(){ public Object doInHibernate(Session session) throws HibernateException { Query query = session.createQuery(hql); return new Integer(query.executeUpdate()); } } )).intValue(); } //执行select语句 public List queryListHql(final String hql) throws DataAccessException { return (List)this.getHibernateTemplate().execute( new HibernateCallback<Object>(){ public Object doInHibernate(Session session) throws HibernateException, SQLException { Query query = session.createQuery(hql); return query.list(); } } ); } public void saveOrUpdateHql(Object obj) { getHibernateTemplate().saveOrUpdate(obj); } public Serializable saveHql(Object obj) { return getHibernateTemplate().save(obj); } public void deleteHql(Object obj) { getHibernateTemplate().delete(obj); } }
这样在操作数据库的service层,我们就可以继承这个MyHibernateDao,并使用里面的方法了。
大多数action层不会直接继承ActionSupport(在学习struts2时我们直接继承这个ActionSupport)。
一般情况下,在业务层就是action里,我们会有一些常用的方法,比如比session的操作,登录用户信息的获取等,
这些常用的方法如果每次用到都重新写一遍那真是代码太过冗余,而且也不好维护,把这些方法封装在BaseAction里,
我们只需要把业务的action继承这个BaseAction就可以使用这些方法了。
MyBaseAction
package org.base; import java.io.PrintWriter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class MyBaseAction extends ActionSupport { private static final long serialVersionUID = 1L; public ActionContext getActionContext() throws Exception{ return ActionContext.getContext(); } public HttpSession getHttpSession() throws Exception{ ActionContext ctx = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); return request.getSession(); } public HttpServletRequest getHttpServletRequest() throws Exception{ ActionContext ctx = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); return request; } public HttpServletResponse getHttpServletResponse() throws Exception{ ActionContext ctx = ActionContext.getContext(); HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); return response; } public PrintWriter getPrintWriter() throws Exception{ ActionContext ctx = ActionContext.getContext(); HttpServletResponse response = (HttpServletResponse) ctx.get(ServletActionContext.HTTP_RESPONSE); PrintWriter out = response.getWriter(); return out; } /////////////////////////////ActionContext取值放值////////////////////////////////////////////// public Object getValueFromActionContext(String key) throws Exception{ ActionContext ac = ActionContext.getContext(); if(key==null||key.trim().equals("")){ return null; }else{ return ac.get(key.trim()); } } public void setValueToActionContext(String key,Object obj) throws Exception{ ActionContext ac = ActionContext.getContext(); if(key==null||key.trim().equals("")){ }else{ ac.put(key.trim(), obj); } } /////////////////////////////HttpSession取值放值////////////////////////////////////////////// public Object getValueFromSession(String key) throws Exception{ ActionContext ctx = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); HttpSession session=request.getSession(); if(key==null||key.trim().equals("")){ return null; }else{ return session.getAttribute(key.trim()); } } public void setValueToSession(String key,Object obj) throws Exception{ ActionContext ctx = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); HttpSession session=request.getSession(); if(key==null||key.trim().equals("")){ }else{ session.setAttribute(key.trim(), obj); } } /////////////////////////////HttpServletRequest取值放值////////////////////////////////////////////// public Object getValueFromRequest(String key) throws Exception{ ActionContext ctx = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); if(key==null||key.trim().equals("")){ return null; }else{ return request.getAttribute(key.trim()); } } public void setValueToRequest(String key,Object obj) throws Exception{ ActionContext ctx = ActionContext.getContext(); HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST); if(key==null||key.trim().equals("")){ }else{ request.setAttribute(key.trim(), obj); } } }
测试功能模块,代码过多,还是另起一篇吧。