Spring data jpa commit in normal java application? - java

When using spring and spring data jpa in a normal java application how will jpa know when to commit the data to the database?
I ask this because repository.save() doesn't commit.
Should i manually commit or can spring handle this for me?
My application context xml:
<context:component-scan base-package="...">
</context:component-scan>
<jpa:repositories base-package="..." entity-manager-factory-ref="emf" />
<bean id="emf" class="...spring.MyEMF"></bean>
<!-- Add Transaction support -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="emf" />
</bean>
<!-- Use #Transaction annotations for managing transactions -->
<tx:annotation-driven transaction-manager="transactionManager" />
I manually init my context with:
new ClassPathXmlApplicationContext("classpath:/data.xml")

No spring can handle transaction for you just before your method repository.save() add #Transactional
#Transactional
public void save(){
//do something
}
and in your configuration class make sure that spring transaction handling is enabled
#EnableTransactionManagement
class myConfig{
}

Related

spring #Transactional with jdbcTemplate in Java [duplicate]

I'm new to Spring and I'm wondering if its possible to use numerous transaction managers in the same application?
I have two data access layers - one for both of the databases. I'm wondering, how do you go about using one transaction managers for one layer and different transaction manager for the other layer. I don't need to perform transactions across both databases - yet. But I do need perform transactions on each database individually. I've created an image to help outline my problem:
Here is my application context configuration:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
<context:component-scan base-package="cheetah.repositories" />
<tx:annotation-driven />
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="accounts" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
</beans>
Here is an example that uses this configuration:
#Repository
public class JpaAccountRepository implements AccountRepository {
#PersistenceContext(unitName = "cheetahAccounts")
private EntityManager accountManager;
#Override
#Transactional
public Account findById(long id) {
Account account = accountManager.find(Account.class, id);
return account;
}
}
So for the account repository, I want to use an entity manager factory with the persistence unit set to accounts. However, with my BusinessData Repository, I want to use an entity manager factory with a different persistence unit. Since I can only define one transaction manager bean, how can I go about using different transaction managers for the different repositories?
Thanks for any help.
Where you use a #Transactional annotation, you can specify the transaction manager to use by adding an attribute set to a bean name or qualifier. For example, if your application context defines multiple transaction managers with qualifiers:
<bean id="transactionManager1"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory1" />
<qualifier value="account"/>
</bean>
<bean id="transactionManager2"
class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory2" />
<qualifier value="businessData"/>
</bean>
You can use the qualifier to specify the transaction manager to use:
public class TransactionalService {
#Transactional("account")
public void setSomethingInAccount() { ... }
#Transactional("businessData")
public void doSomethingInBusinessData() { ... }
}
This Spring Jira entry discusses the issue a bit:
https://jira.spring.io/browse/SPR-3955
I think it could be one transaction manager per connection if you're not using two-phase commit. You just need to create two transaction managers and inject them with the appropriate connection.
But I must ask the question: why do you think you need two transaction managers? You can have more than one database connection. The DAOs that use the connections can and should be instantiated by different services, each of which can be annotated with their own transactional settings. One manager can accommodate both. Why do you think you need two?

Spring #Transactional + jdbcTemplate calling a web service

My application is currently using Spring's JdbcTemplate and #Transaction annotation for transaction handling.
I have a method that calls a web service on a single transaction, and I designed it so that exceptions from the web service will rollback all database changes within the transaction.
my question: how can i FLUSH the database changes made before calling my web service?
many thanks
#Autowired
private MyDao dao;
#Transactional
#Override
public void myMethod() {
.....
dao.saveThis(myObjectToSaveIsNotAnIssue);
// I need to FLUSH here in order for my web service to "see" the saved object
callWebservice();
}
My spring config:
<context:component-scan base-package="com.xxx.xxx" />
<context:annotation-config />
<!-- proxy-target-class is set to true to use transactional scope -->
<tx:annotation-driven proxy-target-class="true" transaction-manager="tomcatTransactionManager" />
<bean id="sybaseDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/xxx"/>
<property name="lookupOnStartup" value="true"/>
<property name="proxyInterface" value="javax.sql.DataSource"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="sybaseDataSource"/>
</bean>
<!-- Transaction Manager -->
<bean id="tomcatTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="sybaseDataSource" />
</bean>
JDBC doesn't have any "flushing" concept. The SQL queries are executed when you execute them. Nothing to be flushed is kept in memory.
Your web service won't see anything in database that you hasn't been committed, due to transaction isolation (which is READ_COMMITTED by default). You'll have to set the isolation level to READ_UNCOMMITTED if that's really what you want (in the web service):
#Transactional(isolation = Isolation.READ_UNCOMMITTED)
We can take out callWebservice() method out of transaction in an assembler and then myMethod can called first from assembler, followed by callWebService() method.
And withinCall Webservice method, we can handle the success and failure scenarios. (Eg: update the status)

how to use transaction of spring to rollback the changes when checked exception is caught?

I am working on a application having JSF, Spring and Hibernate framework.
I'm trying to test transaction of Spring using following method.
#Override
#Transactional(rollbackFor=UnsupportedOperationException.class, propagation=Propagation.REQUIRED)
public void updateActiveMonth(Long collectionMonthId) throws Exception{
try{
Session session = getSessionFactory().getCurrentSession();
String hql = "update CollectionMonth collectionMonth set active = false";
Query query = session.createQuery(hql);
query.executeUpdate();
if (true) {
throw new UnsupportedOperationException();
}
String hql1 = "update CollectionMonth collectionMonth set collectionMonth.active = true where collectionMonth.id=:collectionMonthId";
Query query1 = session.createQuery(hql1);
query1.setLong("collectionMonthId", collectionMonthId);
query1.executeUpdate();
}catch(UnsupportedOperationException e){
throw e;
}
}
Above method suppose to rollback the update made by first query but this doesn't happen.
In application context I have following settings
<context:annotation-config/>
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
p:location="/WEB-INF/jdbc.properties" />
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}"/>
<!-- PERSISTENCE SUPPORT HERE (Hibernate 4 Mapping In Spring ) -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
p:dataSource-ref="dataSource"
p:configLocation="/WEB-INF/hibernate.cfg.xml"
p:packagesToScan="collection.model"/>
<!-- Transaction Manager is defined -->
<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"
p:sessionFactory-ref="sessionFactory" />
<!-- Enable the configuration of transactional behavior based on annotations -->
<tx:annotation-driven transaction-manager="transactionManager"/>
can anybody tell me what am I doing wrong?
I suppose you forgot to declare your class as spring bean, so the spring container is able to detect and register them. Your method public void updateActiveMonth(Long collectionMonthId) must be part of some kind of service or dao class which is somewhere declared for spring.
There are several ways of doing this like declaring these in xml or by setting the proper annotations using annotation-config and component-scan.
I can recommend reading this great article from beginning to the end.

TransactionRequiredException: no transaction is in progress with Spring Data JPA

I looked around for similar problems but couldn't find a solution for this:
I have a Spring Data JPA application that whenever I try to do a trasaction I get javax.persistence.TransactionRequiredException: no transaction is in progress.
I believe it has something to do with the Transaction Manager or Entity Manager Factory, but can't put my finger on it.
The context files are here (latest checked in are here), but here is the part that matters:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSourceMySQL" />
<property name="persistenceUnitName" value="spring-jpa" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="generateDdl" value="true" />
<property name="showSql" value="true" />
<property name="database" value="MYSQL" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSourceMySQL"/>
</bean>
<bean id="dataSourceMySQL" 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/dbname"/>
<property name="username" value="user"/>
<property name="password" value="pass"/>
</bean>
<jpa:repositories base-package="com.simplecash.dal.repository" />
A sample Repository is here and then created a Repository Factory here, which I'm not sure if I need...
Then use it here (line 34).
public void populateWithTestData() {
Bank bank = new Bank();
bank.setName("ContentName");
bank.setCode("ContentCode");
RepositoryFactory.getEntityManager().getTransaction().begin();
BankRepository bankRepository = RepositoryFactory.getRepository(BankRepository.class);
bankRepository.save(bank);
bankRepository.flush();
RepositoryFactory.getEntityManager().getTransaction().commit();
}
A couple of things are wrong above, but I I've tried fixing it and can't:
Begin and Commit transactions are explicit.
bankRepository should be #Autowired, but when I do that I get null. However, in this testcase it is Autowired and works.
Has anyone faced a similar problem and knows what's going on?
Thanks a ton for taking the time to read this. Hope the answer to this question will help other folks.
Both answer provided here offer good points (using injection to get the proxied beans and using transaction-annotations), however, I'm pretty sure that for the annotation-driven transactions to work (#Transactional), you need to add the following to your xml-configuration:
<tx:annotation-driven transaction-manager="transactionManager"/>
Also make sure to add the tx-namespace in your beans-tag:
<beans
<!-- SNIP, other namespaces -->
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
<!-- SNIP, other locations -->
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
I think that in your setup the Transactions are managed by JTA, so you can't explicitly start/stop them (i.e. em.getTransaction().begin() will not work). Try telling Spring that you want a certain method to be part of a (JTA managed) transaction via annotation , like:
#Transactional
public void populateWithTestData() {
//...
}
Begin and Commit transactions are explicit.
What Spring does with your repository beans ( e.g. BankRepository ), it creates a proxy around it, and then it is ready to be injected into other collaborators, which in your case is DatabaseManagerDAO. However if you create the object yourself like you do:
BankRepository bankRepository = RepositoryFactory.getRepository(BankRepository.class);
Instead of expected Spring's proxy ( that already does transaction management for you ), you are getting a simple object that is not aware of anything beyond it is immediate declaration.
What you need to do instead is to trust Spring to do the plumbing for you and just inject a bankRepository bean into a DatabaseManagerDAO (although I don't really think you need both DAO and Repository, since those terms really mean the same thing :)
Repository Factory here, which I'm not sure if I need...
No need for another abstraction. Just inject it as a bean to whatever component needs it.
bankRepository should be #Autowired, but when I do that I get null. However, in this testcase it is Autowired and works.
In a case where it works you run your test with AbstractTransactionalJUnit4SpringContextTests, which knows about 'bankRepository' bean, hence autowires it. In your DatabaseManagerDAO, I see neither autowiring nor a setter for the bankRepository, in fact you create it manually from the factory.
EDIT to answer comments
What jpa:repositories in your XML config really does => it scans the package and creates Spring beans for each component that is either annotated as #Repository or implements a Repository interface.
With that in mind, what you should do in order to use a BankRepository repository in your DatabaseManagerDAO is to inject it. You can do it via "autowiring":
#Service
public class DatabaseManagerDAO {
#Autowired
BankRepository bankRepository;
...
}
instead of manually creating it trough your factory.
Again, DatabaseManagerDAO in your case is probably a service ( #Service ), and not a DAO, but I'll leave it up to you to decide on that.
Notice that a DatabaseManagerDAO should also be loaded by Spring in order for the autowiring to work, so make sure it has one of the Spring annotations ( #Service / #Component ) when you package scan it ( e.g. <context:component-scan base-package="org.example"/> ).
I had a similar issue when combining spring-batch and spring-jpa. In my batch XML, I had this line:
<bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
which caused an error since JPA needs a PlatformTransactionManager.

Using a DAO on a Bean used by a Spring Scheduled Task

I'm developing a web application using Struts2 + Spring, and now I'm trying to add a scheduled task. I'm using Spring's task scheduling to do so. In my applicationContext I have:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
...
</bean>
<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="database" value="MYSQL" />
</bean>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
And then I have my DAO that uses this entityManagerFactory:
<bean id="dao" class="data.GenericDAO" />
So this works flawlessly within the web application. But now I have a problem when creating the scheduled task:
<task:scheduled-tasks scheduler="notifier">
<task:scheduled ref="emailService" method="sendMail" fixed-rate="30000" />
</task:scheduled-tasks>
<task:scheduler id="notifier" pool-size="10" />
<bean id="emailService" class="services.emailService" >
<property name="dao" ref="dao" />
</bean>
This executes the method sendMail on my emailService class every 30 seconds. And my emailService has the DAO injected correctly. The thing is that I can fetch objects with my DAO using the findById named queries, but when I try to access any property mapped by Hibernate, such as related collections or entities, I get an "LazyInitializationException: could not initialize proxy - no Session ". I don't know what's wrong, since I believe the scheduled task is being managed by Spring, so it should have no problem using a Spring managed DAO. I must say that I'm using the openSessionInView filter on my struts actions, so maybe I need something similar for this scheduled task.
Any help or suggestion will be appreciated, thanks!
Edit: Finally I found a way to fix this. I changed my regular Dao with one where I can decide when to start and commit the transaction. So before doing anything I start a transaction and then everything works OK. So I still don't know exactly what causes the problem and if someday I'll be able to use my regular DAO, for the moment I'm staying with this solution.
OpenSessionInView won't help you, because you don't have a web context. You need Spring's Declarative Transaction Management.
In most cases, what you need to do is just this XML:
<!-- JPA, not hibernate -->
<bean id="myTxManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="myTxManager" />
<!-- without backing interfaces you probably also need this: -->
<aop:config proxy-target-class="true">
(Annotate your EmailService class as #Transactional to enable this)

Categories