框架技术--S2SH如何引入多个数据源

在使用S2SH框架中如何配置多个数据源。

简述思路:

  1. 因为hibernate是与我们底层数据库做交互的框架,所以我们要将多个库的连接信息,录入到*hibernate.cfg.xml配置文件中。
  2. 因为hibernate是有spring托管,所以还要在spring的applicationContext.xml中进行配置,告诉spring要管理哪些数据源、怎么管理(事物)。
  3. 在dao层查询数据库时,配置相应信息告诉dao要查询哪一个库的信息。
代码如下:

这里我将两个数据源分别配置2个hibernate的xml,如下

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>

	<session-factory>
		<property name="connection.url">
			jdbc:mysql://192.168.200.27:3306/liveEpg?useUnicode=true&characterEncoding=UTF-8
		</property>
		<property name="connection.username">root</property>
		<property name="connection.password">root</property>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<!-- 
			解决由于长时间没人操作系统,导致hibernate与mysql连接超时,导致连接断开的问题。begin
			参考网站使用c3p0进行一下配置:
			http://blog.csdn.net/nethibernate/article/details/6658855
		 -->
		<!-- c3p0在我们使用的Hibernate版本中自带,不用下载,直接使用 -->  
	    <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>  
	    <property name="hibernate.c3p0.min_size">5</property>  
	    <property name="hibernate.c3p0.max_size">20</property>  
	    <property name="hibernate.c3p0.timeout">1800</property>  
	    <property name="hibernate.c3p0.max_statements">50</property>  
	    <!-- 下面这句很重要,后面有解释 -->  
	    <property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
		<!-- 解决由于长时间没人操作系统,导致hibernate与mysql连接超时,导致连接断开的问题。end -->
		
		<mapping class="com.gp.bean.TUser" />
		
		<mapping class="com.haier.bean.TestPortal" />
		
		<mapping class="com.haier.bean.AdvInfoDetailDto" />
		<mapping class="com.haier.bean.AdvInfoDto" />
		<mapping class="com.haier.bean.AdvRuleBusinessDto" />
		<mapping class="com.haier.bean.AdvRuleDto" />
		<mapping class="com.haier.bean.Channel_infoDto" />
		<mapping class="com.haier.bean.AdvTimeDto" />
		<mapping class="com.haier.bean.AdvCityDto" />
		<mapping class="com.haier.bean.AdvProvinceDto" />
		<mapping class="com.haier.bean.AdMenuDto" />
		<mapping class="com.haier.bean.AdvNumDto" />
		<mapping class="com.haier.bean.MacForTestDto" />
		<mapping class="com.haier.bean.AdvInfoDetailHisDto" />
		<mapping class="com.haier.bean.AdvInfoHisDto" />
		<mapping class="com.haier.bean.AdvRuleHisDto" />
		<mapping class="com.haier.bean.MaterialDto" />
		<mapping class="com.haier.bean.AdvLogDto" />
	</session-factory>

</hibernate-configuration>

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
	<session-factory>
		<property name="connection.url">
			jdbc:mysql://192.157.151.56:3306/haierdb?useUnicode=true&characterEncoding=UTF-8
		</property>
		<property name="connection.username">permitdbuser</property>
		<property name="connection.password">permitdbpwd</property>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<!-- 
			解决由于长时间没人操作系统,导致hibernate与mysql连接超时,导致连接断开的问题。begin
			参考网站使用c3p0进行一下配置:
			http://blog.csdn.net/nethibernate/article/details/6658855
		 -->
		<!-- c3p0在我们使用的Hibernate版本中自带,不用下载,直接使用 -->  
	    <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>  
	    <property name="hibernate.c3p0.min_size">5</property>  
	    <property name="hibernate.c3p0.max_size">20</property>  
	    <property name="hibernate.c3p0.timeout">1800</property>  
	    <property name="hibernate.c3p0.max_statements">50</property>  
	    <!-- 下面这句很重要,后面有解释 -->  
	    <property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
		<!-- 解决由于长时间没人操作系统,导致hibernate与mysql连接超时,导致连接断开的问题。end -->
		
		<mapping class="com.haier.bean.Ad_admin_rightDto" />
		<mapping class="com.haier.bean.Ad_op_code_rightDto" />
		<mapping class="com.haier.bean.Ad_admin_userDto" />
	</session-factory>

</hibernate-configuration>
在spring中配置信息如下:
<?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:p="http://www.springframework.org/schema/p"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
	http://www.springframework.org/schema/aop 
	http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
	http://www.springframework.org/schema/tx 
	http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-2.5.xsd">

	<context:component-scan base-package="com"></context:component-scan>
	<context:component-scan base-package="com.haier"></context:component-scan>
	
	<!-- dataSource注入到sessionFactory -->
	<!-- liveEpg数据源 start -->
	<bean id="liveEpgsessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="configLocation" value="classpath:liveEpg_hibernate.cfg.xml"></property>
	</bean>
	<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="liveEpgsessionFactory"></property>
	</bean>

	<bean id="txManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref bean="liveEpgsessionFactory" />
		</property>
	</bean>

	<tx:advice id="txAdvice" transaction-manager="txManager">
		<tx:attributes>
			<tx:method name="query*" read-only="true" />
			<tx:method name="search*" read-only="true" />
			<tx:method name="find*" read-only="true" />
			<tx:method name="get*" read-only="true"/>
			<tx:method name="show*" read-only="true"/>
			<tx:method name="save*" />
			<tx:method name="update*" />
			<tx:method name="delete*" />
			<tx:method name="add*" />
			<tx:method name="generate*"/>
			<tx:method name="verify*"/>
			<tx:method name="check*"/>
		</tx:attributes>
	</tx:advice>
	<!-- liveEpg数据源 END -->
	
	<!-- uas数据源BEGIN -->
	<bean id="uasEpgsessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="configLocation" value="classpath:uas_hibernate.cfg.xml"></property>
	</bean>
	<bean id="uasHibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
		<property name="sessionFactory" ref="uasEpgsessionFactory"></property>
	</bean>
	
	<bean id="uasTxManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory">
			<ref bean="uasEpgsessionFactory" />
		</property>
	</bean>

	<tx:advice id="uasTxAdvice" transaction-manager="uasTxManager">
		<tx:attributes>
			<tx:method name="query*" read-only="true" />
			<tx:method name="search*" read-only="true" />
			<tx:method name="find*" read-only="true" />
			<tx:method name="get*" read-only="true"/>
			<tx:method name="show*" read-only="true"/>
			<tx:method name="save*" />
			<tx:method name="update*" />
			<tx:method name="delete*" />
			<tx:method name="add*" />
			<tx:method name="generate*"/>
			<tx:method name="verify*"/>
			<tx:method name="check*"/>
		</tx:attributes>
	</tx:advice>
	<!-- uas数据源END -->
	<aop:config>
		<aop:pointcut expression="execution(* com.gp.service.*.*(..))"
			id="serviceMethod" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod" />
	</aop:config>
	<aop:config>
		<aop:pointcut expression="execution(* com.haier.service.*.*(..))"
			id="haierServiceMethod" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="haierServiceMethod" />
		<aop:advisor advice-ref="uasTxAdvice" pointcut-ref="haierServiceMethod" />
	</aop:config>
	
	<!-- 初始化广告信息 -->
	<bean id="getChannelInfo" class="com.haier.timer.GetChannelInfo" lazy-init="false"
		scope="singleton" init-method="execute">
	</bean>
	
</beans>
在dao层进行查询时,代码如下,注意第30行要指定数据源的名字。
package com.haier.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.haier.bean.Ad_admin_rightDto;
import com.haier.bean.Ad_admin_userDto;
import com.haier.dao.Ad_admin_rightDao;
import com.haier.util.PageUtil;
import com.haier.vo.PageVo;

@Repository("ad_admin_rightDao")
public class Ad_admin_rightDaoImpl implements Ad_admin_rightDao {

	private HibernateTemplate uasHibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return uasHibernateTemplate;
	}

	@Resource(name = "uasHibernateTemplate")
	public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
		this.uasHibernateTemplate = hibernateTemplate;
	}

	@Override
	public void delete(Ad_admin_rightDto ad_admin_rightDto) throws Exception {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		session.delete(ad_admin_rightDto);
	}

	@Override
	public List<Ad_admin_rightDto> find() throws Exception {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		Query query = session.createQuery(" from Ad_admin_rightDto aard");
		List<Ad_admin_rightDto> aardList = query.list();
		return aardList;
	}

	@Override
	public void update(Ad_admin_rightDto ad_admin_rightDto) throws Exception {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		session.update(ad_admin_rightDto);
	}

	@Override
	public void save(Ad_admin_rightDto ad_admin_rightDto) throws Exception {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		session.save(ad_admin_rightDto);
	}

	/**
	 * 生成新的roleId
	 * 
	 * @return
	 * @throws Exception
	 */
	public List getNewRoleId() throws Exception {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		StringBuffer sb = new StringBuffer();
		sb.append("select max(role_id),max(id) from ad_admin_right ");
		SQLQuery query = session.createSQLQuery(sb.toString());
		List roleList = query.list();
		return roleList;
	}

	/**
	 * 根据条件查询
	 * 
	 * @param advId
	 * @return
	 */
	public PageVo findByConditions(String conditions, PageVo pageVo)
			throws Exception {
		Session session = getHibernateTemplate().getSessionFactory()
				.getCurrentSession();
		StringBuffer sb = new StringBuffer();
		sb.append("select id, role_id, user_role, opcode, parent_opcode, system_type"
				+ " from ad_admin_right aau where 1=1");
		sb.append(conditions);
		if (pageVo != null) {
			PageUtil.generateConditions(pageVo, sb);
		}
		SQLQuery query = session.createSQLQuery(sb.toString());
		List<Object[]> aldList = new ArrayList<Object[]>();
		List<Ad_admin_rightDto> adRightList = new ArrayList<Ad_admin_rightDto>();
		aldList = query.list();
		Ad_admin_rightDto ad_admin_rightDto;
		for (int i = 0; i < aldList.size(); i++) {
			ad_admin_rightDto = new Ad_admin_rightDto();
			ad_admin_rightDto.setId((Integer) (aldList.get(i))[0]);
			ad_admin_rightDto.setRole_id((Integer) (aldList.get(i))[1]);
			ad_admin_rightDto.setUser_role((String) (aldList.get(i))[2]);
			ad_admin_rightDto.setOpcode((Integer) (aldList.get(i))[3]);
			ad_admin_rightDto.setParent_opcode((Integer) (aldList.get(i))[4]);
			ad_admin_rightDto.setSystem_type((Integer) (aldList.get(i))[5]);
			adRightList.add(ad_admin_rightDto);
		}
		if (pageVo != null) {
			PageUtil.generatePageNum(pageVo);
		} else {
			pageVo = new PageVo();
		}
		pageVo.setAdvInfoVoList(adRightList);
		return pageVo;
	}
}

你可能感兴趣的:(框架)