EJB之JPA(跨越多个MYSQL数据库,)
这个与配置文件有关,在JBOSS5中.需要更新下面配置文件
在JBOSS5+JDK6的环境下,要跨越多个mysql的数据库,需要使用xa-datasource(能支持两阶段提交协议的数据源)
为了使用xa-datasource,请下载最新的mysql驱动(目前是:5.1.13),因此为了测试本项目,请按以下步骤操作:
1、首先替换原来的mysql驱动为新的5.1.13
2、在JBOSS的deploy目录下,增加一个mysql-xa-ds.xml文件,文件的模板如下,请自行修改其中的JNDI名称和用户名、密码、数据库等
-------------------
<?xml version="1.0" encoding="UTF-8"?> <!-- See http://www.jboss.org/community/wiki/Multiple1PC for information about local-tx-datasource --> <!-- $Id: mysql-ds.xml 88948 2009-05-15 14:09:08Z jesper.pedersen $ --> <!-- Datasource config for MySQL using 3.0.9 available from: http://www.mysql.com/downloads/api-jdbc-stable.html --> <datasources> <xa-datasource> <jndi-name>MySqlDS1</jndi-name> <xa-datasource-property name="URL">jdbc:mysql://localhost:3306/ejb31</xa-datasource-property> <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class> <user-name>root</user-name> <password>root</password> <track-connection-by-tx>true</track-connection-by-tx> <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name> <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name> <min-pool-size>1</min-pool-size> <max-pool-size>10</max-pool-size> <idle-timeout-minutes>10</idle-timeout-minutes> <metadata> <type-mapping>mySQL</type-mapping> </metadata> </xa-datasource> <xa-datasource> <jndi-name>MySqlDS2</jndi-name> <xa-datasource-property name="URL">jdbc:mysql://localhost:3306/ejb32</xa-datasource-property> <xa-datasource-class>com.mysql.jdbc.jdbc2.optional.MysqlXADataSource</xa-datasource-class> <user-name>root</user-name> <password>leadfar</password> <track-connection-by-tx>true</track-connection-by-tx> <exception-sorter-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLExceptionSorter</exception-sorter-class-name> <valid-connection-checker-class-name>org.jboss.resource.adapter.jdbc.vendor.MySQLValidConnectionChecker</valid-connection-checker-class-name> <min-pool-size>1</min-pool-size> <max-pool-size>10</max-pool-size> <idle-timeout-minutes>10</idle-timeout-minutes> <metadata> <type-mapping>mySQL</type-mapping> </metadata> </xa-datasource> </datasources>
package cn.com.leadfar.jpa; import javax.ejb.Remote; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless(name="userManager") @Remote public class UserManagerImpl implements UserManager { /** * 如果只定义了一个Persistence Unit,则无需指定unitName,但一旦定义了 * 多个,则必须指定unitName */ @PersistenceContext(unitName="test") private EntityManager em; @PersistenceContext(unitName="test2") private EntityManager em2; public void addUser() { User user = new User(); user.setName("张三"); em.persist(user); Person person = new Person(); person.setName("Test Person"); em2.persist(person); //如果抛出异常,将会导致整个事务回滚!这就是跨越数据库的事务管理 //throw new RuntimeException("异常"); } }