Spring + RMI + transactions + weblogic - spring

We have developed two web services (A,B) with Spring 3, Hibernate 4 & JPA.
Inside a method of service A we need to call to an method of service B. The access is through RMI.
The problem is that the two of them need to be in the same transaction. I think we followed all of the rules dealing with transactions but we cannot rollback the method in service B when service A crashes after method in service B is called.
If an exception is thrown in service A after service B is called the data that service A has changed is rolled back, but not the data changed by service B. It seems that the transaction is renewed in service B and not included in that created in service B.
We use a jndi datasource created in weblogic.
The transactional methods are annotated with:
*#Transactional( readOnly = false, isolation=Isolation.SERIALIZABLE,
rollbackFor=Exception.class, propagation = Propagation.REQUIRED )*
Here is my configuration dealing with transactions:
spring-server.xml (the only data that differs from service to service is the persistence-unit name):
*<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SAPOY/SANOT" />
</bean>
<bean id="jtaTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="allowCustomIsolationLevels" value="true"/>
<property name="globalRollbackOnParticipationFailure" value="true" />
</bean>
<tx:annotation-driven transaction-manager="jtaTransactionManager" proxy-target-class="true" />
<!-- Servicio SAPOY.SANOT -->
<bean id="sanot" class="com.sems.sapoy.sanot.services.impl.Sanot">
<property name="sanotBiz" ref="sanotBiz" />
</bean>*
persistence.xml (the only data that differs from service to service is the persistence-unit name):
*<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="SAPOY/SANOT" transaction-type="JTA">
<description>Unidad de Persistencia del modulo SANOT</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/xaDS</jta-data-source>
<properties>
<!--
################################################################
HIBERNATE
################################################################
-->
<property name="hibernate.archive.autodetection" value="class" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.query.factory_class"
value="org.hibernate.hql.classic.ClassicQueryTranslatorFactory" />
<property name="hibernate.format_sql" value="true" />
<property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect" />
<property name="hibernate.autoReconnect" value="true" />
<property name="hibernate.autoReconnectForPools" value="true" />
<property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.WeblogicTransactionManagerLookup" />
<property name="hibernate.transaction.factory_class" value="org.hibernate.transaction.JTATransactionFactory" />
<!--
################################################################
CONNECTION
################################################################
-->
<property name="hibernate.connection.autocommit" value="false"/>
<!--
################################################################
CACHE
################################################################
-->
<property name="hibernate.cache.use_second_level_cache" value="true" />
<property name="hibernate.cache.region.factory_class" value="net.sf.ehcache.hibernate.EhCacheRegionFactory" />
<property name="hibernate.cache.use_query_cache" value="true" />
</properties>
</persistence-unit>
</persistence>*

Your DataSource/TransactionManager configurations are just fine, the only problem is that you call your other service through RMI.
The global transactions must be coordinated from the same running Thread that may enlist one or more Resources (JDBC connections/JMS queues), but it cannot span over multiple threads.
The moment you call a RMI method, that call is going to be served by a RMI server which assigns a working thread to service your RMI request. Even if that method is #Transactional the transaction will be defined at the RMI working thread boundary.
Try removing the RMI call and it will work. Implementing it over multiple servers is not a trivial thing to do. You'd probably have to use something like the Command pattern, so that the Service A can call Service B to undo when Service A fails to commit. Like I said, this is not as trivial as a global XA transaction. It requires careful design and it may lead to inconsistencies to due undos happening after other transaction already used the already committed changes.
For that you need WS-Transactions and a Application server to support it. By itself JTA manages global transactions on a Thread basis. To span transactions over multiple Threads you need a higher-level protocol like WS-Transactions.

Related

Spring Data Repository caching results

I am a complete spring data noob. I have an interface as follows
public interface UserBalanceRepository extends PagingAndSortingRepository<UserBalance, Integer>
{
#Cachable("UserList")
#Query("select userId from UserBalance")
List<Integer> ListUserIds(Pageable pageable);
}
My cache configuration looks like this:
<cache:annotation-driven />
<!-- generic cache manager -->
<bean id="cacheManager" class="org.springframework.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="org.springframework.cache.concurrent.ConcurrentCacheFactoryBean" p:name="UserList"/>
</set>
</property>
</bean>
The caching does absolutely nothing. I guess it is because the proxied class does not have the #Cachable annotation, but how do I make the caching work? Is there a different way to do caching?
My last resort will be to put the calls that need to be cached inside a wrapper class and cache there.
I was facing the same issue. Your code is the same with mine. I am using eclipseLink and i had to enable caching on persistence.xml too. I just added a property,
[...]
<class>com.project.web.model.entity.ReturnOrder</class>
<class>com.project.web.model.entity.BillingAddress</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://connection string"/>
<property name="javax.persistence.jdbc.user" value="user"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.password" value="pass"/>
<!-- PROPERTY ADDED -->
<property name="eclipselink.cache.shared.default" value="true"/>
</properties>
</persistence-unit>
</persistence>
Also, this is a very good tutorial.

Using jndi with jpa and spring on glassfish

I have a web application that runs on glassfish 3.1. I am using JPA (Hibernate) configured with spring.
This is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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 http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="myPU">
<class>org.myCompany.entities.Class1</class>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
This is part of my ApplicationContext.xml:
<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/myDataSource" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="myPU" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
In addition i have declared my datasource in the glassfish server (jdbc connection pool and recourse)
and the JNDI name is "jdbc/myDataSource". The issue is that on my local installation of glassfish, published via the glassfish plugin for eclipse, it works fine BUT when i deploy the war file manually on an installation of glassfish (i tried on my VPS - CentOS) then i get this error:
Error occurred during deployment: Exception while preparing the app : Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: java.sql.SQLException: Connection could not be allocated because: java.net.ConnectException : Error connecting to server localhost on port 1527 with message Connection refused. Error Code: 0. Please see server.log for more details.
For some reason, the application is using the default derby datasource of glassfish and not my defined datasource. anyone knows why and how to overcome this?
Did you configure your JDBC Resource to use the right Connection Pool? There is a default derby pool configured. Maybe you just selected the wrong pool for your resource?

Exception while creating EntityManagerFactory - Lookup failed for 'persistence/myPU' in SerialContext

I'm working with Glassfish application server and trying to connect my spring-hibernate web application to my db, I have the following configurations:
In Glassfish I have added a jdbc connection and send a successful ping to the DB.
I also added a JDBC resource (in glassfish) with jndi name: jdbc/myResource. This resource is under the connection pool in which I have created and tested (in step 1).
My EntityManaget is annotated with #PersistenceContext:
#PersistenceContext(unitName = "myPU")
protected EntityManager entityManager;
Under \src\main\resources\META-INF\ I created my persistence.xml file:
<persistence-unit name="myPU">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>jdbc/myResource</jta-data-source>
<properties>
<!-- Glassfish transaction manager lookup -->
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.SunONETransactionManagerLookup" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"></property>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.default_schema" value="PUBLIC" />
<property name="hibernate.format_sql" value="true" />
<!-- Validates the existing schema with the current entities configuration -->
<property name="hibernate.hbm2ddl.auto" value="validate" />
</properties>
</persistence-unit>
This is how my applicationContext looks like:
bean id="txManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<jee:jndi-lookup id="emf" jndi-name="persistence/myPU" />
<!-- In order to enable EntityManager injection -->
<bean
class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor">
<property name="persistenceUnits">
<map>
<entry key="myPU" value="persistence/myPU" />
</map>
</property>
</bean>
In my web.xml I have:
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/myPU</persistence-unit-ref-name>
<persistence-unit-name>myPU</persistence-unit-name>
When I publish I keep getting:
No bean named 'myPU' is defined. Please see server.log for more details.
Why is it looking for the persistence unit as a bean?
Any ideas what am I doing wrong?
Thanks in advance
Resolved - I added transaction-type="JTA" to my persistence.xml.
For some reason I was under the impression that if I'm specifying a jta-data-source in my persistence.xml the default transaction-type should be "JTA", maybe it isn't. I don't really understand the relation of the exception I had to this solution but at the moment my persistence.xml has the following line:
<persistence-unit name="myPU" transaction-type="JTA">
And it works like a charm.

Spring + Spring Data JPA Configuration

currently I'm fooling around with a Spring setup. My goal is to use JPA to get access to a Websphere datasource using it's JNDI name. I'm using Spring Data JPA to make life easier for me and worked through some tutorials to get the basic idea.
Bad thing: none of those is talking about the Spring configuration for my JPA szenario + I never worked with JPA / JDBC before.
So I hope you can help me out here. I got 2 configuration files:
applicationContext.xml
<bean id="txManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
<bean id="eManager" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean"></bean>
Since i'm using the #Transactual annotion within my code, i'm using the annotation-driven tag for the txManager. I'm just not really sure what else i should configure for the txManager and what the sessionFactory tag is doing. Is there any documentation for all supported XML tags? Am I missing a importent tag for my szenario?
Same about eManager - not sure if thats right in any way.
persistence.xml
<persistence version="1.0"
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 http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="spring-jpa">
<jta-data-source>jdbc/myJNDI</jta-data-source>
</persistence-unit>
</persistence>
Same thing here: don't really know what i'm doing. I know i need a persistence unit / provider. I know that many are using hibernate for this, but i would like to stay native and use pure JavaEE / Spring if possible.
I'm just not sure how to configure that.
Currently my project is crashing, telling me: "JPA PersistenceProvider returned null"
The best way is to obtain the EntityManagerFactory from the JNDI via Spring's JNDI support:
<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/myPersistenceUnit" />
<jpa:repositories base-package="com.acme.repositories" />
<tx:jta-transactionManager />
This will cause the transaction manager being used from the application server as well. You can also try to setup a JpaTransactionManager and wire the EntityManagerFactory obtained from JNDI into it. You can pull even more configuration into your Spring config files if you only lookup the datasource through an <jee:jndi-lookup /> namespace element and follow the further configuration instructions in the Spring Data JPA reference documentation. Nevertheless it's usually better to use the container resources you can actually get if you decide to use container resources at all.
I just started working with Spring, jpa mysql etc... and I might be able to help you out.
I'll show you the way that I have my configuration right know.
I'm using hibernate by the way for my database connection, I've never did it without so no help from me there :)
My configuration:
Spring-config.xml:
<context:component-scan base-package="com.MYPACKAGE"/>
<!-- To find all your controllers -->
<tx:annotation-driven/>
<!-- This will pickup all your #Transactional annotations-->
<import resource="../database/DataSource.xml"/>
<import resource="../database/Hibernate.xml"/>
<!-- These are my database config files-->
Datasource.xml:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/DATABASENAME"/>
<property name="username" value="USERNAME"/>
<property name="password" value="PASSWORD"/>
</bean>
Hibernate.xml:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false"/>
<property name="generateDdl" value="true"/>
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect"/>
</bean>
</property>
</bean>
I left out the standard xml text that you need to include at the top of your .xml files, but I trust you to work that out yourself ;)
This setup works for me and I hope it can help you out!
If you have any question regarding this post please let me know!
Good luck!
for those using JBoss, the jndi names can be set in persistence.xml properties like this:
<persistence-unit name="punit" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/myDS/jta-data-source>
<class>com.company.model.Document</class>
<class>com.company.model.DocumentIndividual</class>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create" />
<!-- <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/> -->
<property name="javax.persistence.logging.level" value="INFO" />
<property name="hibernate.show_sql" value="true" />
<property name="jboss.entity.manager.jndi.name" value="java:/my_em"/>
<property name="jboss.entity.manager.factory.jndi.name" value="java:/my_emf"/>
</properties>
</persistence-unit>
as described in here section 4.4.2

Spring DB2 JPA Entity Manager Problem

I'm trying to configure Spring, JPA and DB2 in order to have the entity manager instance to be used in my spring controllers but according how I have configured Spring this not happens.
These are the two attempts of configuration of spring:
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource" />
<bean name="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="em" />
</bean>
<bean id="em"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="fileUtility" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter">
<property name="database" value="DB2" />
<property name="showSql" value="true" />
</bean>
</property>
</bean>
the second is this:
<!-- Entity manager factory bean. -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="Sample" />
</bean>
<!-- Entity manager bean. -->
<bean id="em" factory-bean="entityManagerFactory"
factory-method="createEntityManager" />
and the entity manager is injected in this way:
<bean id="messageService" class="utilities.services.impl.MessageServiceImpl">
<property name="entityManager" ref="em" />
</bean>
but I have always this exception:
Caused by: java.lang.IllegalArgumentException: methods with same signature createEntityManager() but incompatible return types: [interface com.ibm.websphere.persistence.WsJpaEntityManager, interface org.apache.openjpa.persistence.OpenJPAEntityManagerSPI]
I don't know how can be fixed. Has anyone encountered this problem?
Thanks in advance.
[EDIT]
This is my persistence.xml:
<?xml version="1.0"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">
<persistence-unit name="fileUtility"
transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<mapping-file>META-INF/mapping.xml</mapping-file>
<properties>
<property name="openjpa.ConnectionURL" value="jdbc:db2://localhost:50000/db2admin" />
<property name="openjpa.ConnectionDriverName" value="COM.ibm.db2.jdbc.app.DB2Driver" />
<property name="openjpa.ConnectionUserName" value="db2admin" />
<property name="openjpa.ConnectionPassword" value="XXXX" />
<property name="openjpa.FlushBeforeQueries" value="true"/>
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
</properties>
</persistence-unit>
<persistence-unit name="fileUtility2" transaction-type="JTA">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<jta-data-source>file_ds</jta-data-source>
<mapping-file>META-INF/mapping.xml</mapping-file>
<properties>
<property name="openjpa.Log" value="SQL=TRACE"/>
<property name="openjpa.ConnectionFactoryProperties" value="PrettyPrint=true, PrettyPrintLineLength=72"/>
</properties>
</persistence-unit>
</persistence>
WebSphere has a JPA implementation bundled. So no need to add openjpa to your lib. In fact, WebSphere is using OpenJPA, so you are not losing anything. Look here for more details
When using a jda-data-source, you need to have transaction-type="JTA". Also, you should not specify connection properties - they are specified in the datasource.
And get rid of the <provider> - the document I linked says:
If no JPA provider is configured in the element of the persistence.xml file within an EJB module, the default JPA provider that is currently configured for this server is used
I believe you're doing the wrong configuration, because you're configuring it "à la Tomcat". If you're using a Java EE application server, such as WAS, you should:
In Spring application context xml file
configure the DAO bean by a <bean> definition
configure the JNDI definition for the datasource created in the application server via a
<jee:jndi-lookup>
definition; the
name
attribute should be
persistence/XXX, where XXX shall match the
<persistence-unit name="XXX" transaction-type="JTA">
in persistence.xml file
The id attribute in the
<jee:jndi-lookup id=YYY> should point to the
name=YYY parameter of the Entity Manager definition in the DAO, this is to say,
#PersistenceContext(name=YYY) EntityManager em;
Specify
<tx:annotation-driven /> and
<tx:jta-transaction-manager />
In file
web.xml of your web app you should include a definition using the xml tag
<persistence-unit-ref> whose
<persistence-unit-ref-name> parameter shall be the
persistence/XXX JNDI name as specified in persistence.xml (shown above).
Finally, you should create a JNDI definition in the application server (AS dependant) that defines the JNDI name for the JDBC connection. This name should match the
<jta-data-source> xml tag in the persistence.xml file, and it is the only link between the JPA definition and the JDBC defined in the application server.
To round up:
Application Context Spring file
<bean class="DAO implementation class" />
<jee:jndi-lookup id="YYY" jndi-name="persistence/XXX" />
<tx:annotation-driven />
<tx:jta-transaction-manager />
persistence.xml file
<persistence-unit name="XXX" transaction-type="JTA">
<jta-data-source>jdbc/DSN</jta-data-source>
</persistence-unit>
web.xml file
...
<persistence-unit-ref>
<persistence-unit-ref-name>persistence/XXX</persistence-unit-ref-name>
</persistence-unit-ref>
...
DAO (only #PersistenceContext shown)
...
#PersistenceContext(name = "YYY")
EntityManager em;
...
Application Server: jdbc/DSN links to the connection definition, where the driver for the DBM is. Depends on both the AS and the DBM used.
Thus, you may see the connection between the DAO -> Spring Application Context file -> persistence.xml and web.xml files -> Application Server JNDI names. IF you're using a full Java EE application server (such as WAS, Weblogic or GlassFish) you don't have to use Spring interface modules; only defnitions in the app server (see Spring documentation, section 12.6.3).

Resources