Atomikos多数据源配置项目实例

applicationContext.xml

<?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:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
	http://www.springframework.org/schema/jee
	http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.0.xsd"
	default-lazy-init="true">

	<description>Spring公共配置 </description>

	<!-- 定义受环境影响易变的变量 -->
	<bean
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
		<property name="ignoreResourceNotFound" value="true" />
		<property name="locations">
			<list>
				<!-- 标准配置 -->
				<value>classpath*:/application.properties</value>
				<!--
					集群中节点配置 <value>classpath*:/application.cluster.properties</value>
				-->

				<!--
					本地开发环境配置 <value>classpath*:/application.local.properties</value>
				-->

				<!--
					服务器生产环境配置 <value>/pom/application.server.properties</value>
				-->

			</list>
		</property>
	</bean>

	<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->
	<context:component-scan base-package="com.wiseweb.pom" />

	<!-- orable配置 -->
	<!-- <bean id="dataSourceContent" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
        <property name="uniqueResourceName">
            <value>jdbc/dataSourceContent</value>
        </property>
        <property name="xaDataSourceClassName">
            <value>oracle.jdbc.xa.client.OracleXADataSource</value>
        </property>
        <property name="xaProperties">
            <props>
                <prop key="URL">${jdbc.url}</prop>
                <prop key="user">${jdbc.username}</prop>
                <prop key="password">${jdbc.password}</prop>
            </props>
        </property>
        <property name="poolSize">
            <value>5</value>
        </property>
        <property name="maxPoolSize">
			<value>15</value>
		</property>
    </bean>
    <bean id="dataSourceIndex" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
        <property name="uniqueResourceName">
            <value>jdbc/dataSourceIndex</value>
        </property>
        <property name="xaDataSourceClassName">
            <value>oracle.jdbc.xa.client.OracleXADataSource</value>
        </property>
        <property name="xaProperties">
            <props>
                <prop key="URL">${jdbc.url}</prop>
                <prop key="user">${jdbc.username}</prop>
                <prop key="password">${jdbc.password}</prop>
            </props>
        </property>
        <property name="poolSize">
            <value>5</value>
        </property>
        <property name="maxPoolSize">
			<value>15</value>
		</property>
    </bean> -->

	<!-- 本地数据库配置 -->
	<bean id="dataSourceContent" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
        <property name="uniqueResourceName">
            <value>jdbc/dataSourceContent</value>
        </property>
        <property name="xaDataSourceClassName">
            <value>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</value>
        </property>
        <property name="xaProperties">
            <props>
                <prop key="serverName">${jdbc.servername}</prop>
                <prop key="portNumber">${jdbc.portnumber}</prop>
                <prop key="databaseName">${jdbc.databasename}</prop>
                <prop key="user">${jdbc.username}</prop>
                <prop key="password">${jdbc.password}</prop>
            </props>
        </property>
        <property name="poolSize">
            <value>5</value>
        </property>
        <property name="maxPoolSize">
			<value>15</value>
		</property>
        <property name="testQuery">
			<value>select 1</value>
		</property>
    </bean>
    <bean id="dataSourceIndex" class="com.atomikos.jdbc.AtomikosDataSourceBean" init-method="init" destroy-method="close">
        <property name="uniqueResourceName">
            <value>jdbc/dataSourceIndex</value>
        </property>
        <property name="xaDataSourceClassName">
            <value>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</value>
        </property>
        <property name="xaProperties">
            <props>
                <prop key="serverName">${jdbc.servername_index}</prop>
                <prop key="portNumber">${jdbc.portnumber_index}</prop>
                <prop key="databaseName">${jdbc.databasename_index}</prop>
                <prop key="user">${jdbc.username_index}</prop>
                <prop key="password">${jdbc.password_index}</prop>
            </props>
        </property>
        <property name="poolSize">
            <value>5</value>
        </property>
        <property name="maxPoolSize">
			<value>15</value>
		</property>
        <property name="testQuery">
			<value>select 1</value>
		</property>
    </bean>

	<!-- 数据源配置,使用应用内的DBCP数据库连接池
	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		 Connection Info
		<property name="driverClassName" value="${jdbc.driver}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		 Connection Pooling Info
		<property name="maxIdle" value="${dbcp.maxIdle}" />
		<property name="maxActive" value="${dbcp.maxActive}" />
		<property name="defaultAutoCommit" value="false" />
		<property name="timeBetweenEvictionRunsMillis" value="3600000" />
		<property name="minEvictableIdleTimeMillis" value="3600000" />
	</bean>

	--><!-- 数据源配置,使用应用服务器的数据库连接池 -->
	<!--
		<jee:jndi-lookup id="dataSource"
		jndi-name="java:comp/env/jdbc/ExampleDB" />
	-->

	<!-- Hibernate配置
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="namingStrategy">
			<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
		</property>
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">${hibernate.dialect}</prop>
				<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
				<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
				<prop key="hibernate.cache.use_second_level_cache">${hibernate.use_second_level_cache}</prop>
				<prop key="hibernate.cache.use_query_cache">${hibernate.use_query_cache}</prop>
				<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
				<prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache/ehcache-hibernate-local.xml</prop>
			</props>
		</property>
		<property name="packagesToScan" value="com.wiseweb.pom.entity" />
	</bean>

	-->
	<!-- Hibernate配置 -->
	<!-- 本地数据库Hibernate配置 -->
    <bean id="sessionFactoryContent" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSourceContent" />
        <property name="namingStrategy">
            <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache/ehcache-hibernate-local.xml</prop>
            </props>
        </property>
        <property name="packagesToScan" value="com.wiseweb.pom.entity" />
    </bean>
    <!-- 远程数据库Hibernate配置 -->
    <bean id="sessionFactoryIndex" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSourceIndex" />
        <property name="namingStrategy">
            <bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
                <prop key="hibernate.cache.provider_configuration_file_resource_path">ehcache/ehcache-hibernate-local.xml</prop>
            </props>
        </property>
        <property name="packagesToScan" value="com.wiseweb.pom.entity" />
    </bean>

	<!-- 事务管理器配置,单数据源事务
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>
 	-->

 	<!-- ActiveMQ JMS服务 -->
	<!--创建连接工厂-->
    <bean id="connectionFactory"
        class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://127.0.0.1:61616"></property>
    </bean>
    <!-- 声明ActiveMQ队列消息目标-->
    <!-- <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
    	<constructor-arg index="0" value="wiseweb.queue"></constructor-arg>
    </bean> -->
    <!-- 声明ActiveMQ主题消息目标 -->
    <bean id="destination" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg index="0" value="wiseweb.topic"></constructor-arg>
    </bean>
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory"></property>
        <property name="defaultDestination" ref="destination"></property>
        <property name="receiveTimeout" value="10000"></property>
    </bean>
    <!-- 消息监听适配器 -->
    <bean id="messageListenerAdapter" class="org.springframework.jms.listener.adapter.MessageListenerAdapter">
    	<property name="delegate">
    		<bean class="com.wiseweb.pom.jms.listener.MessageListener"></bean>
    	</property>
    	<property name="defaultListenerMethod" value="receiveMessage"></property>
    	<property name="defaultResponseDestination" ref="destination"></property>
    </bean>
    <!-- 监听容器 -->
    <!-- <bean id="messageListenerContainer" class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    	<property name="connectionFactory" ref="connectionFactory"></property>
    	<property name="destination" ref="destination"></property>
    	<property name="messageListener" ref="messageListenerAdapter"></property>
    </bean> -->
    <bean id="messageSender" class="com.wiseweb.pom.jms.MessageSender">
    	<property name="jmsTemplate" ref="jmsTemplate"></property>
    </bean>

	<!-- 事务管理器配置,多数据源JTA事务-->
    <bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close">
        <property name="forceShutdown"><value>true</value></property>
    </bean>   

    <bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp">
        <property name="transactionTimeout" value="300"/>
    </bean>
    <bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
        <property name="transactionManager" ref="atomikosTransactionManager" />
        <property name="userTransaction" ref="atomikosUserTransaction"/>
        <property name="allowCustomIsolationLevels" value="true"/>
    </bean>

	<!-- 使用annotation定义事务 -->
	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />

	<!-- 加载网站类型 -->

	<bean id="groupMap" class="java.util.TreeMap">
		<constructor-arg>
			<map>
				<entry key="1" value="新闻" />
				<entry key="2" value="论坛" />
				<entry key="3" value="博客" />
				<entry key="4" value="微博" />
				<entry key="5" value="纸媒" />
		   <!-- <entry key="6" value="视频" />-->
		   		<entry key="7" value="外媒" />
		   <!-- <entry key="8" value="广播" />
				<entry key="9" value="电视" />
				<entry key="10" value="空间" />
				<entry key="11" value="微信" />-->
			</map>
		</constructor-arg>
	</bean>

	<bean id="staticValue" class="com.wiseweb.util.StaticValue"
		lazy-init="false">
		<property name="groupMap">
			<ref bean="groupMap" />
		</property>
	</bean>

	<bean id="hibernateDaoImple" class="com.wiseweb.pom.dao.HibernateGeneralDao">
		<property name="sessionFactory" ref="sessionFactoryContent"></property>
	</bean>

	<!-- 配置定时器 -->
	<bean id="scheduler"
		class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	</bean>
	<bean id="quartzTimerUtil" class="com.wiseweb.util.sms.QuartzTimerUtil">
		<property name="scheduler" ref="scheduler" />
	</bean>
	<bean id="startAllTimer" class="com.wiseweb.util.sms.StartAllTimer">
		<property name="scheduler" ref="scheduler" />
		<property name="hibernateDaoImple" ref="hibernateDaoImple"></property>
	</bean>
	<!-- 配置定时器结束 -->
</beans>

dao层

package com.wiseweb.pom.dao.account;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.springframework.stereotype.Component;
import org.springside.modules.orm.hibernate.HibernateDao;

import com.wiseweb.pom.entity.Company;
/**
 * HibernateDao中的Company是实体类
 * @author Benjamin
 *
 */
@Component
public class CompanyDao  extends HibernateDao<Company, Long>
{
	//选择applicationContext中名为sessionFactoryContent的sessionFactory注入,实现多数据源访问
	@Override
	@Resource(name = "sessionFactoryContent")
    public void setSessionFactory(SessionFactory sessionFactory) {
        // TODO Auto-generated method stub
        super.setSessionFactory(sessionFactory);
    }
}

实体类entity

package com.wiseweb.pom.entity;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Transient;

@Entity
@Table(name="wise_company")
public class Company implements Serializable{
	/**
	 *
	 */
	private Long id ;
	private static final long serialVersionUID = 1L;
	private String name ;
	private Integer grade ;
	private Long parentId ;
	private Integer nodeType ;
	private Integer orderType ;
	private Integer flag ;
	private Company fCompany ;
	private List<Department> departments = new ArrayList<Department>() ;
	private Long companyNum ;
	private Long childNum ;
	private List<Company> childCompanys = new ArrayList<Company>() ;
	@Column(name="name", nullable=false, length=45)
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	@Column(name="grade", nullable=false)
	public Integer getGrade() {
		return grade;
	}
	public void setGrade(Integer grade) {
		this.grade = grade;
	}
	@Column(name="parent_id", nullable=false)
	public Long getParentId() {
		return parentId;
	}
	public void setParentId(Long parentId) {
		this.parentId = parentId;
	}
	@Column(name="node_type", nullable=false)
	public Integer getNodeType() {
		return nodeType;
	}
	public void setNodeType(Integer nodeType) {
		this.nodeType = nodeType;
	}
	@Column(name="order_type")
	public Integer getOrderType() {
		return orderType;
	}
	public void setOrderType(Integer orderType) {
		this.orderType = orderType;
	}
	@Column(name="flag", nullable=false)
	public Integer getFlag() {
		return flag;
	}
	public void setFlag(Integer flag) {
		this.flag = flag;
	}
	@OneToMany(mappedBy="company",cascade = {CascadeType.ALL})
	public List<Department> getDepartments() {
		return departments;
	}
	public void setDepartments(List<Department> departments) {
		this.departments = departments;
	}
	@Transient
	public Company getFCompany() {
		return fCompany;
	}
	public void setFCompany(Company fCompany) {
		this.fCompany = fCompany;
	}
	@Id
	public Long getId() {
		return id;
	}
	public void setId(Long id) {
		this.id = id;
	}
	@Transient
	public Long getCompanyNum() {
		return companyNum;
	}
	public void setCompanyNum(Long companyNum) {
		this.companyNum = companyNum;
	}
	@Transient
	public List<Company> getChildCompanys() {
		return childCompanys;
	}
	public void setChildCompanys(List<Company> childCompanys) {
		this.childCompanys = childCompanys;
	}
	@Transient
	public Long getChildNum() {
		return childNum;
	}
	public void setChildNum(Long childNum) {
		this.childNum = childNum;
	}

}

下面最重要的是service层,必须要加上@Transactional不然会报the XA resource is currently involved in a local (non-XA) transaction的错误。

@Component
@Transactional
public class AccountManager {
	...
}

最后就可以通过指定不通的sessionFactory访问不同的数据库了。

时间: 2024-12-28 02:18:42

Atomikos多数据源配置项目实例的相关文章

java开源框架SpringSide3多数据源配置的方法详解

原创整理不易,转载请注明出处:java开源框架SpringSide3多数据源配置的方法详解 代码下载地址:http://www.zuidaima.com/share/1781579130801152.htm 在SpringSide 3社区中,不断有人提出多数据源配置的问题,但是时至今日却一直没有一个完美的答案.经过一个星期的折腾,我总算搞清楚了在SpringSide 3中配置多数据源的各种困难并加以解决,在这里,特地把我配置SpringSide 3项目中多数据源的过程写出来,与大家分享. 我使用

SpringSide 3 中的多数据源配置的问题

在SpringSide 3 中,白衣提供的预先配置好的环境非常有利于用户进行快速开发,但是同时也会为扩展带来一些困难.最直接的例子就是关于在项目中使用多个数据源的问题,似乎很难搞.在上一篇中,我探讨了SpringSide 3 中的数据访问层,在这一篇中,我立志要解决多数据源配置的难题,我的思路是这样的: 第一步.测试能否配置多个DataSource第二步.测试能否配置多个SessionFactory第三步.测试能否配置多个TransactionManager第四步.测试能否使用多个Transac

SpringSide3中多数据源配置

applicationContext.xml中配置 下面是加载外部配置文件:application.properties <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OV

spring boot 多数据源配置(多种数据库)

最近一段时间在使用spring boot开发项目,其中有一个项目用到了多数据源的配置,网上的资料还是不太多,走了好多才找到一个合适的,把自己写的分享一下,做个笔记,以后也许有用,第一次写博客,不好勿喷!! 首先介绍下我的业务场景,此项目用到了两种数据库,一个是mysql,另一个是sqlserver, 首先第一步需要在application.yml中将多数据源的配置信息进行配置, mysql数据源: spring: datasource: driverClassName: com.mysql.jd

spring 4 + jpa(hibernate 3/4) + spring mvc 多数据源配置

先从persistence.xml开始: <?xml version=”1.0″ encoding=”UTF-8″?><persistence version=”2.1″ xmlns=”http://java.sun.com/xml/ns/persistence” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation=”http://java.sun.com/xml/ns/persistence

spring+mybatis最简多数据源配置

作者:纯洁的微笑出处:http://www.ityouknow.com/ 版权所有,欢迎保留原文链接进行转载:) 说起多数据源,一般都来解决那些问题呢,主从模式或者业务比较复杂需要连接不同的分库来支持业务.我们项目是后者的模式,网上找了很多,大都是根据jpa来做多数据源解决方案,要不就是老的spring多数据源解决方案,还有的是利用aop动态切换,感觉有点小复杂,其实我只是想找一个简单的多数据支持而已,折腾了两个小时整理出来,供大家参考. 废话不多说直接上代码吧 配置文件 pom包就不贴了比较简

使用idea创建SSM项目时数据源配置异常

异常:org.springframework.jdbc.CannotGetJdbcConnectionException jdbc.properties关于DB的配置(数据库名是liaody): driverClassName=com.mysql.jdbc.Driver password=root username=root url=jdbc:mysql://localhost:3306/liaody?characterEncoding=UTF8 applicationContext.xml关于

atomikos的Jta配置

配置说明见: http://www.atomikos.com/Documentation/JtaProperties atomikos的一些配置,文档中说明的比较清楚,有两个属性配置不太明确:com.atomikos.icatch.max_timeout.com.atomikos.icatch.default_jta_timeout都是关于事务超时的,验证了一下第一个配置有效的,当事务运行时间超过该时间配置时,会抛错.com.atomikos.jdbc.AtomikosSQLException:

Spring Boot之JdbcTemplate多数据源配置与使用

之前在介绍使用JdbcTemplate和Spring-data-jpa时,都使用了单数据源.在单数据源的情况下,Spring Boot的配置非常简单,只需要在application.properties文件中配置连接参数即可.但是往往随着业务量发展,我们通常会进行数据库拆分或是引入其他数据库,从而我们需要配置多个数据源,下面基于之前的JdbcTemplate和Spring-data-jpa例子分别介绍两种多数据源的配置方式. 多数据源配置 创建一个Spring配置类,定义两个DataSource