JTA 2PC - with multiple datasource - spring

I am new to JTA and i am trying to implement the JTA 2 pc .In business method
I want if fun1 fails then fun3 should also but its not happening.
#Transactional
fun(){
testDao1.fun1();
testDao2.fun3();
}
I had following things .
Create datasource as .I have multiple datasources
<bean id="dataSource" class="org.apache.commons.dbcp.managed.BasicManagedDataSource"
destroy-method="close">
<property name="driverClassName" value="org.postgresql.xa.PGXADataSource" />
<property name="url" value="${database.interimws.email.url}" />
<property name="username" value="${database.interimws.email.username}" />
<property name="password" value="${database.interimws.email.password}" />
<property name="defaultAutoCommit" value="false" />
<property name="maxActive" value="${database.maxactive}" />
<property name="maxIdle" value="${database.maxidle}" />
<property name="maxWait" value="${database.maxwait}" />
</bean>
having persistence unit which is of JTA type
created entityAMangerFactory using the above dataSource and Persistence unit
4.getting the javax.transaction.TransactionManager and Usertransaction object from Server and configured spring jta for annotation
Having a bussiness class which is annotated as transactional.

Make sure that you have XA-type drivers for every database that participates in two-phase commit; otherwise, it won't work.
How are you testing this? Do you have a mock version of DAO1 that throws an exception?

Related

Can we use DBCP 2 or Tomcat connection pool for distributed transactions in Spring? Can these connection pool be used along with JOTM or Atomikos?

Initially i was using different transaction manager for multiple data sources. But i had problem with managing rollback on all data sources if one of the data sources has transaction failure.I want to manage multiple datasources with single Transaction manager in Spring. So i opted for using JOTM or Atomikos. Both these transaction manager uses XA Connection pool(org.enhydra.jdbc.pool.StandardXAPoolDataSource). But in my project i was allowed to use only DBCP 2(org.apache.commons.dbcp.BasicDataSource) or Tomcat Connection Pool(org.apache.tomcat.jdbc.pool.DataSource). Is it possible to use either of this connection pools with JOTM or Atomikos. Please someone help me on this along with configuration example. Below is my configuration details,
<
bean id="jotm" class="org.springframework.transaction.jta.JotmFactoryBean"/>
<bean id="txManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="userTransaction" ref="jotm" />
</bean>
<bean id="dataSource1" class="org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method="shutdown">
<property name="dataSource">
<bean class ="org.enhydra.jdbc.standard.StandardXADataSource " destroy-method ="shutdown">
<property name="transactionManager" ref="jotm" />
<property name="driverName" value="${jdbc.d1.driver}" />
<property name ="url" value = "${jdbc.d1.url}" />
</bean>
</property>
<property name="user" value="${jdbc.d1.username}" />
<property name = "password" value="${jdbc.d1.password}" />
</bean>
<bean id="dataSource2" class="org.enhydra.jdbc.pool.StandardXAPoolDataSource" destroy-method="shutdown">
<property name="dataSource">
<bean class ="org. enhydra.jdbc.standard.StandardXADataSource " destroy-method ="shutdown">
<property name="transactionManager" ref="jotm" />
<property name="driverName" value="${jdbc.d2.driver}" />
<property name="url" value="${jdbc.d2.url}" />
</bean>
</property>
<property name="user" value="${jdbc.d2.username}" />
<property name = "password" value ="${jdbc.d2.password}" />
</bean>
Also do help if any other possible ways to achieve this.

Can configure two DataSoure in a Spring configuration?

I am developing a web application and I need two DataSource to connect two difference database according to my requirement.One DataSource will use Spring + JPA framework and another DataSource is use Spring + MyBatis framework.
Yes you can I suggest manage both from spring and obtained from the applicationContext.
<bean class="org.apache.tomcat.jdbc.pool.DataSource" id="dataSource" >
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
<bean class="org.apache.tomcat.jdbc.pool.DataSource" id="dataSourceOrderDetail" >
<property name="driverClassName" value="${database.driverClassName}"/>
<property name="url" value="${database.url.orderdetail}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</bean>
Just need to have different name of id, to be properly injected
Check this to review how you can integrate spring with ibatis then configure beans using the datasource beans
Or if you want to use datasource-ds.xml just put the two datasource xml files in the lib folder within your application context, if you are using something like jboss or tomcat.
UPDATE
<jpa:repositories base-package="com.staples.sa.pricemart.repository.pag"
entity-manager-factory-ref="entityManagerFactory" />
<bean class="org.springframework.orm.jpa.JpaTransactionManager" id="transactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<qualifier value="pagTransactionManager" />
</bean>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactory">
<property name="persistenceUnitName" value="persistenceUnit" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<jpa:repositories base-package="com.staples.sa.pricemart.repository.orderdetail"
entity-manager-factory-ref="entityManagerFactoryOrderDetail" />
<bean id="transactionManagerOrderDetail" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactoryOrderDetail" />
<qualifier value="orderDetailTX" />
</bean>
<bean
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
id="entityManagerFactoryOrderDetail">
<property name="persistenceUnitName" value="persistenceUnitOrderDetail" />
<property name="dataSource" ref="dataSourceOrderDetail" />
<property name="jpaDialect">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
</property>
</bean>
<!-- -->
Persistence.xml need to look like this. (need to complete the xml config)
<persistence-unit name="persistenceUnit"
transaction-type="RESOURCE_LOCAL">
And
<!-- Add the persistence context for OrderDetail -->
<persistence-unit name="persistenceUnitOrderDetail"
transaction-type="RESOURCE_LOCAL">
Here is the sample code for you
class Main {
public static void main(String args[]) throws Exception {
ApplicationContext ac = new ClassPathXmlApplicationContext("context.xml", Main.class);
DataSource dataSource = (DataSource) ac.getBean("dataSource");
DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");
Context.xml
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
<property name="url" value="jdbc:oracle:thin:#oracle.devcake.co.uk:1521:INTL"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="mysqlDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://dbhost-prospring-psql/prospring"/>
<property name="username" value="sa"/>
<property name="password" value=""/>
</bean>
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler">
<property name="nativeJdbcExtractor" ref="nativeJdbcExtractor"/>
</bean>
<bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor"/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
You can configure as many databases as you like in Spring context by declaring datasource beans with different id's and
injecting appropriate properties from properties file. if the two databases are different then you are in territory of distributed transactions and you must configure a Spring transaction manager which can operate with JTA. Also worth noting is that Spring transaction manager is merely an abstraction and it needs to have external JTA transaction
manager configured (like Bitrionix / Atomikos) or if deploying under EE application server then transaction manager can be looked up in JNDI registry. Then when you mark the transaction boundary (perhaps using Spring Transactional annotation) then Spring would automatically co-ordinate the transactions.

Dynamically (Runtime) change Datasource credentials in Spring Mybatis

I want to dynamically change Datasource properties in Spring+MyBatis project.
Problem is in Spring + MyBatis integration, we cannot set the datasource properties dynamically during runtime.
Currently I'm using the following code to set the credentials:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}" p:username="${jdbc.username}"
p:password="${jdbc.password}" />
I tried options with UserCredentialsDataSourceAdapter to change the password during runtime but I cannot return back the dataSource object to use for the connection as MyBatis
ApplicationContext context = ApplicationContextUtils.getApplicationContext();
UserCredentialsDataSourceAdapter ds = (UserCredentialsDataSourceAdapter) context.getBean("dataSource");
ds.setCredentialsForCurrentThread("test", "test");
I'm stuck here, I cannot use the dataSource element ds to use for making connection for MyBatis. Please help me in resolving this issue.
I suppose that you use mybatis-spring.
Your approach with UserCredentialsDataSourceAdapter is not working because you are using connection pool, so connection is not closed after usage but are returned to the pool and reused later even that you've changed username and password.
To fix this just get rid of pool:
<bean id="targetDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter">
<property name="targetDataSource" ref="targetDataSource"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
and use the later bean in SqlSessionFactoryBean configuration:
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
If you do not use mybatis-spring and use mybatis directly then the problem is to make mybatis use configured DataSource. This can be done by registering dataSource in JNDI and configure mybatis to get DataSource from JNDI.
<bean id="targetDataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${app.jdbc.driverClassName}" />
<property name="url" value="${app.jdbc.url}" />
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.UserCredentialsDataSourceAdapter">
<property name="targetDataSource" ref="targetDataSource" />
<property name="username" value="#{app.jdbc.username}" />
<property name="password" value="#{app.jdbc.password}" />
</bean>
<!-- Declare a transaction manager for Encounter Navigator Authenticator -->
<!-- Enable annotation style of managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- define the SqlSessionFactory for Encounter Navigator Authenticator,
notice that configLocation is not needed when you use MapperFactoryBean -->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
name="sqlSessionFactory">
<property name="dataSource" ref="dataSource" />
<property name="mapperLocations"
value="file:C:/Program Files/Apache Software Foundation/Tomcat 7.0/config/app_user/*.xml" />
<property name="configLocation" value="classpath:sqlmap-config.xml" />
</bean>
<!-- scan for MAPPERS and let them be auto-wired - For Encounter Navigator
Authenticator -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage"
value="com.upmc.health.encounternavigator.dao.authentication" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
UserCredentialsDataSourceAdapter ds = (UserCredentialsDataSourceAdapter) applicationContext.getBean("dataSource");
ds.removeCredentialsFromCurrentThread();
ds.setCredentialsForCurrentThread("test", "test");
ds.setUsername("test");
ds.setPassword("test");
ds.setTargetDataSource(ds);
ds.afterPropertiesSet();
authDao.getDetails(); //This calls an interface and executes the query present in the xml file

How to get spring bean reference to java field automatically

my spring XML is below,
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean id="jTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
I'm creating the spring bean context when the server is starting up. When I hit on the submit button of the JSP page, it should call the servlet and executes the SQL Query.
Without doing JdbcTemplate jTemplate = (JdbcTemplate)context.getBean("jTemplate") is there anyway I can get the jTemplate object automatically injected to my java property?
my java property is this,
private JdbcTemplate jTemplate;
So, simply I want to use the jTemplate without just doing JdbcTemplate jTemplate = (JdbcTemplate)context.getBean("jTemplate")
Sorry guys I'm bit new to Spring, If you don't get what I'm saying please ask me again.
Use autowiring which can be in three ways
By name
By Type
By Constructor
Further reading is available here
like one solution is
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" autowire="byName">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/test" />
<property name="username" value="root" />
<property name="password" value="root" />
</bean>
<bean name="jTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
Use #Autowired annotation to get this bean automatically like this.
#Autowired
private JdbcTemplate jTemplate;

In spring, what code is used to inject the value for the #PersistenceContext annotated variables?

Using a ClassPathXmlApplicationContext object I want to get the same EntityManager that is being used by other parts of the app which get it injected via:
#PersistenceContext(unitName="accessControlDb") private EntityManager em;
Using ctx.getBean("access-emf") I can get the EntityManagerFactory which is defined in the applicationContext.xml. Using that I can create a new EntityManager, but I can't get the existing EntityManager used by the rest of the app.
I just can't figure out what code is executed to inject the value for the #PersistenceContext annotation.
<bean id="jotm" class="org.springframework.transaction.jta.JotmFactoryBean"/>
<bean id="innerNgsdpDataSource" class="org.enhydra.jdbc.standard.StandardXADataSource">
<property name="driverName" value="${ngsdp.jdbc.driver}"/>
<property name="url" value="${ngsdp.jdbc.url}"/>
<property name="user" value="${ngsdp.jdbc.username}"/>
<property name="password" value="${ngsdp.jdbc.password}"/>
<property name="transactionManager" ref="jotm"/>
</bean>
<bean id="ngsdpDataSource" class="org.enhydra.jdbc.pool.StandardXAPoolDataSource">
<property name="transactionManager" ref="jotm"/>
<property name="dataSource" ref="innerNgsdpDataSource"/>
<property name="user" value="${ngsdp.jdbc.username}"/>
<property name="password" value="${ngsdp.jdbc.password}"/>
<property name="maxSize" value="4"/>
<property name="checkLevelObject" value="2"/>
<property name="jdbcTestStmt" value="select 1 from dual"/>
</bean>
<bean id="myEmf" name="moservices" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="ngsdpDataSource"/>
<property name="persistenceXmlLocation" value="WEB-INF/moservices-persistence.xml" />
<property name="jpaVendorAdapter" ref="hibernate_jpa_vendor_adapter" />
<property name="jpaPropertyMap" ref="jpa_property_map"/>
<property name="jpaDialect" ref="hibernate_jpa_dialect"/>
</bean>
If using spring-managed transactions, you can get the current EntityManager by calling
EntityManagerFactory emFactory = ctx.getBean("access-emf");
EntityManagerHolder emHolder =
(EntityManagerHolder) TransactionSynchronizationManager.getResource(emFactory);
EntityManager em = emHolder.getEntityManager();
This is most often the current EntityManager. But this is something which should be avoided (except possibly in unit-tests), as stated in the spring docs:
To be used by resource management code but not by typical application code
Another approach might be to intercept your service calls using Spring AOP, inject the #PersistenceContext in the advice, and set in in a ThreadLocal of yours. Later, you can get it from that ThreadLocal.

Resources