What's the difference between using #Transactional and Spring template? - spring

If I use #Transactional in my DAO will all of my EntityManager queries be encapsulated with commit and close? Or do I need to use Spring template (JPA template, Hibernate template)? What's the difference between using #Transactional and Spring template?

The difference between using annotation-based transaction demarcation (#Transactional) and the TransactionTemplate is that TransactionTemplate couples you to Spring's transaction infrastructure and means that you will programmatically handle setting the transaction status if the transaction should be rolled back. You can use annotation-based transaction demarcation with the Spring transaction support or with AspectJ transactions outside of a Spring container.
See also the online documentation for transactions in Spring.

The Spring template classes are only there to provide a nicer API for doing persistence operations - they do not deal with transactions. If you want to have transactional operations, you either need to use the #Transactional annotation approach, or use TransactionTemplate.

When you use #transactional with the proper Spring configuration, Spring will recognize that the method needs an transaction and will handle the transaction creation, commit and close for you.
Like skaffman said, #transactional is not directly tied to the template classes. They can be used for any class that may need transactions.

do u mean usin #transactional will encapsulate my dao methods with commit,close or when using spring transaction template (jpatemplate, hibernatetemplate) ?

Related

Transaction - Springboot(JHipster) - RestService: how to

I have a microservice created with JHipster(SpringBoot+JPA) exposing a rest api.
During a save operation over an Entity I need to manage the transaction because I must execute another update over the DB (using other Entities).
How can I do this?
Using the tradictional approach (JDBC) I got the connection and create a transaction over it, make all the queries and finally close the transaction(commit/rollback).
With JPA I have an Entity, but I find no way to specify to begin/end(manage) the transaction programmatically.
You have many alternatives, here are few ones:
define a service (a class annotated with #Service) and annotate with #Transactional the public method that implements your logic
manage transaction manually through the EntityManager injected into your service class constructor
create a custom Repository
Check the Spring docs

Using #Transactional in Micronaut without using Hibernate

Micronaut has support for JDBC, and the guide states that #Transactional from micronaut-spring can be used for AOP style transaction handling. I can't get this to work, when using #Transaction with a plain datasource, I get an exception that no TransactionManager is in place.
Do anyone know if I can use plain JDBC with micronaut with #Transactional support?
The reason for this is the DataSource needs to be wrapped in a TransactionAwareDataSourceProxy in order to perform #Transaction
U can try to add smth like this
compile "io.micronaut:spring"
runtime "org.springframework:spring-jdbc"

Why doesnt #Transactional and #RequestMapping work together?

The moment I include the #Transactional annotation on a #RequestMapping, I notice in springboot that the url mappings do not auto-configure.
What could be responsible for this?
I want a case where (C)R(UD) rest calls work within a transaction.
If you're goal is to ensure your CRUD operations happen within a transaction, then using Spring Data JPA, this is done for you by default. Creating a repository interface that extends CrudRepository for example, your query methods will inherently be #Transactional. You can customize the #Transactional attributes by manually annotating a query method on your repository, but this need only be done if you want non default behaviour.
See the Spring Data JPA docs for more details.
http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#transactions

Using Spring+Hibernate for testing purposes

I want to clarify my problem a bit more:
I understand the purposes of using SPring Framework (i.e. container-managed object lifecycle) and also Hibernate (using ORM between Javaobjects and relational database systems - impedance mismatch resolution).
I understand how we autowire an object and Spring takes over the creation and destruction of the object during runtime by looking at the applicationContext.xml file (in addition to persistence.xml file if using Hibernate or any other persistence provider).
What I want to do is the following:
I would like to implement my own shopping service. I already have entity (item) annotated with #Table, #Id, #Column, etc. to tell JPA that this is what will be stored in the database.
I already have a DAO interface (currently only add and delete methods) implemented by a DaoImpl class where I have done the following:
#Repository
#Transactional
public class MyShopDbDaoImpl implements MyShopDbDao {
// The following named unit will be in my persistence.xml file
// Which will be placed in src/main/resources/META-INF folder
#PersistenceContext(unitName="myShopDbDao")
private EntityManager em;
// Getters for em (simply returns em)
// Setters for em (simply assigns an em supplied in the args.)
// Other query method
}
I also have a ShopDbController controller class that uses:
#Autowired
// defined in the applicationContext.xml file
private MyShopDbDao myShopDbDaoImpl
What I am struggling with is the "Understanding" of EntityManagerFactory and EntityManager relationships along with how the transactions must be managed. I know that the following hierarchy is the main starting point to understand this:
Client talks to a controller.
Controller maps the request and gets the entitymanager to do queries and stuff to the database (either a test/local database with JUNIT test etc. or an actual SQL-type database).
What I do know is that transactions can be managed either manually (i.e. beginning, committing, and closing a session) or through Spring container (i.e. using bean defs in applicationContext.xml file). How can I get more information about the entitymanagers and entitymanagerfactory in order to setup my system?
I didn't find the online documentation from Oracle/Spring/Hibernate very helpful. I need an example and the explanation on the relationship between entitymanagerfactory, sessionfactory, entitymanager, and transactionmanager. Could someone please help me with this?
I don't need people to hold my hand, but just put me in a right direction. I have done Spring projects before, but never got to the bottom of some stuff. Any help is appreciated.
EntityManagerFactory will obtain java.sql.Connection objects, through opening/closing new physical connections to the database or using a connection pool (c3p0, bonecp, hikari or whatever implementation you like). After obtaining a Connection, it will use it to create a new EntityManager. The EntityManager can interact with your objects and your database using this Connection and can manage the transaction through calling EntityManager#getTransaction and then calling EntityTransaction#begin, EntityTransaction#commit and EntityTransaction#rollback that internally works with Connection#begin, Connection#commit and Connection#rollback respectively. This is plain vanilla JPA and Spring has nothing to do up to this point.
For transaction management, Spring helps you to avoid opening/closing the transactions manually by using a transaction manager, specifically a class called JpaTransactionManager. This transaction manager will make use of your EntityManagerFactory to open and close a transaction for the EntityManager created for a set of operations. This can be done either using XML configuration or #Transactional annotation on your classes/methods. When using this approach, you won't directly work with your specific classes anymore, instead Spring will create proxies for your classes using cglib and make use of the transaction manager class to open the transaction, call your specific method(s) and execute a commit or rollback at the end, depending on your configuration. Apart of this, Spring provides other configurations like read-only transactions (no data modification operation allowed).
Here's a basic configuration of the elements explained above using Spring/Hibernate/JPA:
<!--
Declare the datasource.
Look for your datasource provider like c3p0 or HikariCP.
Using most basic parameters. It's up to you to tune this config.
-->
<bean id="jpaDataSource"
class="..."
destroy-method="close"
driverClass="${app.jdbc.driverClassName}"
jdbcUrl="${app.jdbc.url}"
user="${app.jdbc.username}"
password="${app.jdbc.password}" />
<!--
Specify the ORM vendor. This is, the framework implementing JPA.
-->
<bean id="hibernateVendor"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
showSql="false"/>
<!--
Declare the JPA EntityManagerFactory.
Spring provides a class implementation for it.
-->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
persistenceXmlLocation="classpath*:META-INF/persistence.xml"
persistenceUnitName="hibernatePersistenceUnit"
dataSource-ref="jpaDataSource"
jpaVendorAdapter-ref="hibernateVendor"/>
<!--
Declare a transaction manager.
Spring uses the transaction manager on top of EntityManagerFactory.
-->
<bean id="transactionManager"
class="org.springframework.orm.jpa.JpaTransactionManager"
entityManagerFactory-ref="entityManagerFactory"/>
From what i see, your em reference should be a functioning proxy object to your database (this EntityManager is the thing that should be a spring bean, having configured everything, like DB url, driver, etc. Apart from this none of your code should depend on what DB you have). You don't need to know about the classes you mention (entitymanagerfactory sessionfactory transactionmanager). Easy example is:
List<MyBean> bean = (List<MyBean>)em.createNamedQuery("select * from mydb").getResultList();
It should be this easy to run a select * query and get your MyBean typed objects straight ahead, without any explicit conversion by you (this is what hibernate is for).
Similar for insert:
em.persist(myBean);
where myBean is something annotated for Hibernate.
Briefly about transactions, i found best to annotate #Transactional on service METHODS (you did it on a whole dao).
To be very very general:
an entitymanagerfactory is an object responsible of the creation of the entitymanager and it comes from the JPA specifications.
SessionFactory is the hibernate implementation of entitymanagerfactory
session is the hibernate implementation of entitymanager
A transacation manager is an object who manages transaction when you want to define a transaction manually.
So if you want to use hibernate, use SessionFactory and session. And if you want you to stay "generic" use the EntityManagerFactory.
http://www.javabeat.net/jpa-entitymanager-vs-hibernate-sessionfactory/
http://www.theserverside.com/tip/How-to-get-the-Hibernate-Session-from-the-JPA-20-EntityManager

Mule 3.3 spring 3.1 hibernate 3.6 transaction management

I am working on an application which involves mule, spring, hibernate with annotations. I am using org.springframework.orm.hibernate3.HibernateTransactionManager. Now the problem is :
I have certain components in mule which logs data into db based on conditions using hibernate. I have used #Transactional which inserts few data and then commits the transaction when the method scope is completed. But the behaviour which i want is : first component inserts data based on some condition, but the transaction should not commit immediately, again my second component that is a java class should insert some data again then third etc. if any of the component fails all the queries executed in all the components should be rolled back. all of this components are separate java classes
How can i achieve such behaviour.
thank you,
Let your whole component execution chain be in a transaction. then it will meet your expectation. it is easy to do it if all your components are in the same one spring appliction context. In the case, there are two things you need to do:
Add #Transactional annotation on your component class or specific methods which need to be in transaction. By default, transactional method use REQUIRED Propagation setting which will let all method in the exection chain merge to only one transaction.
Make sure Spring can scan all your components.
#Transactional
#Component( "lbsProviderApiCallJob" )
public class LbsProviderApiCallJoImpl implements LbsProviderApiCallJob, ApplicationContextAware {
If all your component are not in a spring context. it is complex to make it.

Resources