zoukankan      html  css  js  c++  java
  • JAVAWEB 一一 框架整合(SSH,Spring+Struts2+Hibernate IOC/DI AOP声明式事务处理 定时任务)

    package org.springframework.orm.hibernate3;
    
    import java.io.Serializable;
    import java.util.List;
    
    import org.springframework.orm.hibernate3.HibernateTemplate;
    
    @SuppressWarnings("rawtypes")
    public interface BaseDao<T> {
    	HibernateTemplate getHibernateTemplate();
    
    	Serializable save(T instance);
    	void delete(T instance);
    	void update(T instance);
    	void saveOrUpdate(T instance);
    	T findById(Serializable id);
    	List<T> findAll();
    	List<T> findByProperty(String propertyName, Object value);
    	Object uniqueResult(final String hql,final Object... paras);
    	List findByHql(String hql,Object... paras);
    	Integer executeByHql(final String hql,final Object... paras);
    	List findByHqlInCache(final String hql,final Object... paras);
    	List findPage(final String hql,final int maxResult,final int firstResult,final Object... paras);
    	List findBySQLQuery(final String sql,final Object... paras);
    }
    

      BaseDao.java

    package org.springframework.orm.hibernate3;
    
    import java.io.Serializable;
    import java.lang.reflect.ParameterizedType;
    import java.util.List;
    
    import org.hibernate.HibernateException;
    import org.hibernate.LockMode;
    import org.hibernate.Query;
    import org.hibernate.SQLQuery;
    import org.hibernate.Session;
    import org.hibernate.type.Type;
    import org.springframework.orm.hibernate3.HibernateCallback;
    import org.springframework.orm.hibernate3.HibernateTemplate;
    
    
    /**
     * Dao的基类,封装了绝大多数的数据库操作
     * 命名查询、命名参数查询等在HibernateTemplate已经实现,直接使用即可。
     * 调用存储过程使用命名查询来实现,具体参考Hibernate帮助文档
     * 放在org.springframework.orm.hibernate3下的目的是为了调用HibernateTemplate的protected方法
     *
     * @param <T>
     */
    @SuppressWarnings(value={"rawtypes","unchecked"})
    public abstract class BaseDaoImpl<T> implements BaseDao<T> {
    	private Class<T> entityClass;
    	protected HibernateTemplate hibernateTemplate;
    	
    	public BaseDaoImpl() {
    		//当该类被继承时,它的子类需要初始化T,通过该代码获取T的类型
    		entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];		 
        }
    	
    	public Serializable save(T instance) {
    		return this.hibernateTemplate.save(instance);
    	}
    	
    	public void delete(T instance) {
    		this.hibernateTemplate.delete(instance);
    	}
    	
    	public void update(T instance) {
    		this.hibernateTemplate.update(instance);
    	}
    	
    	public void saveOrUpdate(T instance){
    		//瞬时态则save,游离态则update
    		hibernateTemplate.saveOrUpdate(instance);
    	};
    	
    	public T findById(Serializable id){
    		T instance = hibernateTemplate.get(entityClass, id);
    		return instance;		
    	}
    	
    	/**
    	 * 根据HQL查询,支持单值查询,如使用聚合函数查询
    	 */
    	public List findByHql(String hql,Object... paras) {	
    		 return hibernateTemplate.find(hql, paras);
    	}
    	
    	/**
    	 * 根据HQL进行增删改,支持单值查询,如使用聚合函数查询
    	 * 插入操作只支持INSERT INTO ... SELECT ...形式,不支持INSERT INTO ... VALUES ...形式
    	 * @param hql
    	 * @param paras
    	 * @return 受影响的行数
    	 */
    	public Integer executeByHql(final String hql,final Object... paras) {			
    		return this.hibernateTemplate.executeWithNativeSession(new HibernateCallback<Integer>() {
    			public Integer doInHibernate(Session session) throws HibernateException {
    				Query query = session.createQuery(hql);
    				hibernateTemplate.prepareQuery(query);
    				if (paras != null) {
    					for (int i = 0; i < paras.length; i++) {
    						query.setParameter(i, paras[i]);
    					}
    				}
    				return query.executeUpdate();
    			}
    		});
    	}
    	
    	/**
    	 * 根据HQL使用查询缓存进行查询
    	 */	
    	public List findByHqlInCache(final String hql,final Object... paras) {		
    		return hibernateTemplate.executeWithNativeSession(new HibernateCallback<List>() {
    			public List doInHibernate(Session session) throws HibernateException {
    				Query query = session.createQuery(hql);				
    				hibernateTemplate.prepareQuery(query);
    				query.setCacheable(true);
    				if (paras != null) {
    					for (int i = 0; i < paras.length; i++) {
    						query.setParameter(i, paras[i]);
    					}
    				}
    				return query.list();
    			}
    		});
    	}
    	
    	/**
    	 * 查询数据库中的所有对象
    	 */
    	public List<T> findAll(){
    		String hql = "from "+this.entityClass.getSimpleName();
    		List<T> list = hibernateTemplate.find(hql);
    		return list;
    	};
    	
    	/**
    	 * 根据属性查找
    	 */
    	public List<T> findByProperty(String propertyName, Object value){
    		String hql = "from "+this.entityClass.getSimpleName()+" where "+propertyName+"=?";
    		List<T> list = hibernateTemplate.find(hql,value);
    		return list;
    	}	
    	
    	/**
    	 * 单值查询
    	 */
    	public Object uniqueResult(final String hql,final Object... paras) {
    		return hibernateTemplate.executeWithNativeSession(new HibernateCallback<Object>() {
    			public Object doInHibernate(Session session) throws HibernateException {
    				Query query = session.createQuery(hql);
    				hibernateTemplate.prepareQuery(query);
    				if (paras != null) {
    					for (int i = 0; i < paras.length; i++) {
    						query.setParameter(i, paras[i]);
    					}
    				}
    				return query.uniqueResult();
    			}
    		});
    	}
    	
    	/**
    	 * 分页查询,记录的下标从0开始
    	 */
    	public List findPage(final String hql,final int maxResult,final int firstResult,final Object... paras) {
    		return hibernateTemplate.executeWithNativeSession(new HibernateCallback<List>() {
    			public List doInHibernate(Session session){
    				Query query = session.createQuery(hql);
    				hibernateTemplate.prepareQuery(query);
    				query.setMaxResults(maxResult);
    				query.setFirstResult(firstResult);
    				if(paras != null){
    					for(int i = 0;i<paras.length;i++){
    						query.setParameter(i, paras[i]);
    					}
    				}
    				return query.list();
    			}
    		});
    	}	
    
    	/**
    	 * 使用本地sql语句进行查询,在报表查询、复杂查询时可能用到
    	 * @param sql
    	 * @param paras
    	 * @return
    	 */
    	public List findBySQLQuery(final String sql,final Object... paras) {
    		return hibernateTemplate.executeWithNativeSession(new HibernateCallback<List>() {
    			public List doInHibernate(Session session){
    				SQLQuery query = session.createSQLQuery(sql);				
    				if(paras != null){
    					for(int i = 0;i<paras.length;i++){
    						query.setParameter(i, paras[i]);
    					}
    				}
    				return query.list();
    			}
    		});
    	}
    	
    	/**
    	 * 将对象转化为瞬时态,只能在Transaction激活的时候使用
    	 * @param instance
    	 */
    	private void convertToTransient(T instance) {
    		hibernateTemplate.getSessionFactory().getCurrentSession().lock(instance, LockMode.NONE);
    	}
    
    	public HibernateTemplate getHibernateTemplate() {
    		return hibernateTemplate;
    	}
    
    	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
    		this.hibernateTemplate = hibernateTemplate;
    	}
    	
    	//还可以实现使用jdbc接口查询等功能
    }
    

      BaseDaoImpl.java

    配置文件

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:context="http://www.springframework.org/schema/context"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="http://www.springframework.org/schema/beans 
               http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
               http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-3.1.xsd
               http://www.springframework.org/schema/aop
               http://www.springframework.org/schema/aop/spring-aop-3.1.xsd
               http://www.springframework.org/schema/tx 
         	   http://www.springframework.org/schema/tx/spring-tx-3.1.xsd"
         	   default-lazy-init="false"
         	   default-autowire="no"
         	   >
        
        <!--支持基于注解的配置方式,为@Autowired、@Resource、@PostConstruct、@PreDestroy注解提供支持 --> 	   
        <context:annotation-config/>
      	
      	<!--支持annotation实现aop,并允许为没有实现接口的类实现切面  -->
    	<aop:aspectj-autoproxy proxy-target-class="true" />
    	
    	<bean id="dataSource" destroy-method="close"
    		class="com.mchange.v2.c3p0.ComboPooledDataSource">
    		<!-- 连接数据库的驱动类 -->
    		<property name="driverClass" value="oracle.jdbc.driver.OracleDriver"/>
    		<!-- 连接数据库的url -->
    		<property name="jdbcUrl" value="jdbc:oracle:thin:@localhost:1521:orcl"/>
    		<!-- 连接数据库的用户名 -->
    		<property name="user" value="scott"/>
    		<!-- 连接数据库的密码 -->
    		<property name="password" value="orcl"/>
    		<!-- 连接池的最大连接数 -->
    		<property name="maxPoolSize" value="40"/>
    		<!-- 连接池的最小连接数 -->
    		<property name="minPoolSize" value="1"/>
    		<!-- 初始化连接数 -->
    		<property name="initialPoolSize" value="1"/>
    		<!-- 连接的最大空闲时间,超时的连接将被丢弃,单位:秒 -->
    		<property name="maxIdleTime" value="60"/>
    		<!-- 没有连接可用时,等待连接的时间,单位:毫秒 -->
    		<property name="checkoutTimeout" value="2000"/>
    	</bean>
    
    	<bean id="sessionFactory"
    		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    		<property name="dataSource" ref="dataSource" />		
    		<property name="mappingLocations">
    			<list>
    				<value>classpath:com/ssh/entity/*.hbm.xml</value>
    			</list>
    				
    		</property>
    	</bean>
    	
    	<bean id="hibernateTemplate"
    		class="org.springframework.orm.hibernate3.HibernateTemplate">
    		<property name="sessionFactory" ref="sessionFactory" />
    	</bean>
    	
    	<!-- 为baseDaoImpl注入hibernateTemplate  -->
    	<bean id="baseDao" class="org.springframework.orm.hibernate3.BaseDaoImpl" abstract="true">
    		<property name="hibernateTemplate" ref="hibernateTemplate" />
    	</bean>
    	
     	<!-- 所有dao对象,注意dao需要继承baseDao  -->
    <!-- 	<bean id="groupDao" class="com.pb.dao.impl.GroupDaoImpl" parent="baseDao"></bean>
    	<bean id="userDao" class="com.pb.dao.impl.UserDaoImpl" parent="baseDao"></bean>
    	
    	所有service对象,注意service需要注入dao 
    	<bean id="groupService" class="com.pb.service.impl.GroupServiceImpl">
    		<property name="groupDao" ref="groupDao" />
    	</bean>
    	<bean id="userService" class="com.pb.service.impl.UserServiceImpl">
    		<property name="userDao" ref="userDao" />
    		<property name="groupDao" ref="groupDao" />
    	</bean>	 --> 
    	
    
    	
    	<!--  AOP 辅助功能 比如 日志 事务 性能 等   -->
    	<!-- 声明式事务处理配置  -->
    	<bean id="txManager"
    	 class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    		<property name="sessionFactory" ref="sessionFactory"></property>
    	</bean>
    	<!--  其他的事务处理配置  -->
    	<tx:advice id="txAdvice" transaction-manager="txManager">
    		<tx:attributes>
    			<!-- 匹配所有方法 -->
    			<tx:method name="*" propagation="REQUIRED"/>	
    			<!-- 配置查询方法的事务处理操作为只读 -->
    			<tx:method name="search*"  read-only="true"/>	
    			<!-- 不将getter和setter方法纳入事务处理 -->
    			<tx:method name="get*" propagation="NEVER"/>
    			<tx:method name="set*" propagation="NEVER"/>
    		</tx:attributes>				
    	</tx:advice>
    	<aop:config>
    		<!--  配置链接点 (切入点)  -->
    		<aop:pointcut expression="execution(public * com.ssh.service.*.*(..))"
    		 id="servicepointcut"/>
    		<aop:advisor advice-ref="txAdvice" 
    		pointcut-ref="servicepointcut"/>
    	</aop:config>
    	<!--  控制反转ioc di注入  -->
    	<bean id="userDao" class="com.ssh.dao.impl.UserDaoImpl" parent="baseDao"></bean>
    	<bean id="userService" class="com.ssh.service.impl.UserServiceImpl" >
    		<property name="userDao">
    		<ref bean="userDao"/>
    		</property>		
    	</bean>	
    	<!--  配置Struts2 Action 的bean -->
    	<bean id="userAction" class="com.ssh.action.UserAction" scope="prototype">
    		<property name="service" ref="userService"/>
    	
    	</bean>
    	
    	<bean id="empDao" class="com.ssh.dao.impl.EmpDaoImpl">
    		<property name="hibernateTemplate" ref="hibernateTemplate"/>
    	</bean>
    	<bean id="empService" class="com.ssh.service.impl.EmpServiceImpl">
    		<property name="empDao" ref="empDao"/>
    	</bean>
    	<bean id="empAction" class="com.ssh.action.EmpAction">
    		<property name="empService" ref="empService"/>
    	</bean>
    	
    </beans>
    

      

    接口

    实现类

     声明式事务处理

    定时任务

    IOC/DI

  • 相关阅读:
    集合改变时会自动通知的集合类
    WPF中的MatrixTransform
    WPF中,如何将Vista Aero效果扩展到整个窗口
    WPF中的命令与命令绑定(二)
    参加BEA Dev2Dev TechDays 归来
    在WPF中自定义你的绘制(五)
    Microsoft Surface
    WPF与缓动(二) 正弦与余弦缓动
    WPF与缓动(一) N次缓动
    终于找到了一个WPF中的日历控件
  • 原文地址:https://www.cnblogs.com/PoeticalJustice/p/7816357.html
Copyright © 2011-2022 走看看