What is the point of using spring transaction while we have database level transaction? - spring

What is the point of using spring transaction while we have database level transaction ?
If you use mysql, oracle or any other db in java, they provide methods to make things inside transaction then why spring transaction if I can do transaction using java DB driver methods ?

It's another layer of abstraction over the database transaction API. So if you wanted to use multiple databases with global transactions, Spring would allow you to do this. While I have never done it, I believe it would allow you to use DB2 and Hibernate together, for example.
Generally, what I've found is, if a feature is available in Spring, it's because there is a use case for it. They don't just put things into the framework without a reason.
Also, Spring provides declarative transaction demarcation, which produces more readable and maintainable Java code. The declarative approach lets us change the transaction strategy easily, without changing the code.
The Declarative transaction management approach allows you to manage the transaction with the help of configuration instead of hard coding in your source code. This means that you can separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions
We used Spring AOP along with Hibernate using this transaction strategy Here is an example, Spring AOP transaction mangement with Hibernate.

Related

ReactiveCrudRepository to use Hibernate in spring

Is it possible to use Hibernate and RDBMS(Mysql, Postgres etc) with ReactiveCrudRepository instead of CrudRepository? I have tried some samples with Spring Data Jpa and Hibernate, but couldn't get it done. I was only able to find a few samples on ReactiveCrudRepository for MongoDB and cassandra.
Is it possible to use Hibernate and Mysql with ReactiveCrudRepository instead of CrudRepository?
TL;DR:
Not with Hibernate and MySQL, but with R2DBC and Postgres, Microsoft SQL Server or H2.
Take a look at Spring Data R2DBC.
Long Version
Why not JPA?
With Hibernate/JPA included this won't happen in the foreseeable future.
JPA is based on the idea that you load part of your data model into memory, manipulate the resulting object model and let JPA transform these changes.
All this within a single transaction.
This is kind of the opposite how one deals with a reactive store where you try to make atomic changes and try to decouple the loading, processing and storing and all this without blocking.
Why not JDBC?
So we have to look at the technology level below JPA: JDBC.
But JDBC is still blocking: You send a SQL statement to your database and then JDBC will block until you get the result.
And again this goes against the idea of reactive: Never block.
One could wrap this in a thread pool to mitigate this to some extent, but that is more of a workaround than a solution.
Why R2DBC?
There are some suitable drivers for some databases that could be used for reactive repositories.
But they are proprietary and thereby not a good basis for something that really should eventually work across all (relevant) relational databases.
For some time the Spring Data team hoped that ADBA would fill that gap.
But discussions on the mailing list made it clear that ADBA was not aiming for reactive but only for asynchronous.
Again not what we needed for a reactive repository abstraction.
So early in 2018 various people living at the intersection or reactive and relational decided that we need a standard for reactive database access.
R2DBC (Reactive Relational Database Connectivity)
is a proposal for such a standard.
The hope is that it either helps convincing Oracle to move ADBA to a reactive approach or if that doesn't happen it becomes the standard itself.
And with already three implementations available chances for the second option look promising.
R2DBC itself is mainly an SPI, i.e. an API that is to be implemented by database providers.
The SPI is designed in a way that puts minimal requirements on implementers.
But this also makes R2DBC somewhat cumbersome to use.
The idea is that other libraries will step up and build libraries designed for usability on top of that SPI, as it happened with JDBC.
Spring Data R2DBC
Spring Data R2DBC is one such library and it offers what you asked for: Support for ReactiveCrudRepository although it is independent of JPA/Hibernate and there is no support for MySQL yet.
State of the projects
Both R2DBC and Spring Data R2DBC didn't have a production release yet and it will take at least several months to get there.
Spring Data R2DBC just released the first milestone.
See the release article for its current capabilities.
R2DBC is on its 6th milestone. See the release article for details.
See also this answer: Why does Spring not provide reactive (non-blocking) clients for relational databases?
Original answer as a reference for archeologists:
As of now (Jan 2017) it is not possible.
The currently relevant release for the reactive part of Spring Data is Spring Data Kay M1 (You can check if there is a newer version available on the project home page)
And a blog post from the Spring Data team about that release and specifically the reactive parts in it starts with (emphasis mine):
Spring Data Kay M1 is the first release ever that comes with support for reactive data access. Its initial set of supported stores — MongoDB, Apache Cassandra, and Redis — all ship reactive drivers already, which made them very natural candidates for such a prototype.
The reason is that there is no standard non-blocking way to access a relational database. So only those that support this kind of API are supported right now.
One could implement a ReactiveCrudRepository using JPA or JDBC and delegate the work to a thread pool. This would provide an async API on the outside, but would still consume the resources for the Threads and block between independent data accesses, so only a small part of the benefits of the reactive approach would get realized.
Hibernate started a new Hibernate Reactive subproject for reactive streams support which provides Hibernate/JPA similar APIs to access RDBMS. But unfortunately at the moment, Spring Data does not support it. So there is no a ReactiveCrudRepoisoty for Hibernate Reactive.
But you can integrate Hibernate with Spring yourself and get reactive support.
Define a persistence.xml file, note the provider class must be specified as the one in Hibernate Reactive.
Declare a Mutiny.SessionFactory bean.
Then inject it in your repository class.
I have created a complete example demos Hibernate Reactive + Spring.
Update: Till now Spring team has no plan to support it, if you are willing to taste other framework, check Quarkus and Micronaunt, both have seamless Hibernate Reactive support. Check my Quarkus Hibernate Reactive example and Micronaut Hibernate Reactive example.
According to quote from previous answer
One could implement a ReactiveCrudRepository using JPA or JDBC and delegating the work to a thread pool. This would provide an async API on the outside, but would still consume the resources for the Threads and block between independent data accesses, so only a small part of the benefits of the reactive approach would get realized.
James Ward claims it can be non-blocking. I mean I asked him:
yeah ok, but isn't ScalikeJDBC-Async doing exactly the same? just putting query invocation into another thread pool?
and he replied
No because ScalalikeJDBC-Async uses https://github.com/mauricio... which is actually a non-blocking (NIO) JDBCish database driver.
source
So you can be reactive by replacing hibernate + spring data with postgresql-async (should work with mysql).
you could try with quarkus framework and panache mongo hibernate reactive repositories. https://quarkus.io/guides/mongodb-panache .It is easy manage a reactive repository over mongoDB, It is later but hope helps.

Transitioning to Spring Data

We are currently using Spring 3.2.3 + JPA (Hibernate). We use aspects for transaction support as opposed to annotations. We write out own entity services (read: repositories) to abstract the persistence away from our application.
I've read a lot about Spring Data and feel it would make our code considerably cleaner and more robust. I wonder though, are there any gotchas that I should consider before transitioning?
Thanks
If you're already on JPA the transition should be as easy as it can be: activate the repositories, point the infrastructure to your EntityManagerFactoryBean and off you go.
Transactions should just work fine as well. The annotation based usage within Spring Data is selectively activated for the repository beans only. They are configured to take part in existing transactions by default, so any custom larger scoped transaction setting should be in effect already.

Declarative or Programmatic Transaction in Spring

What type of transaction management strategy we should use in Spring?
Declarative or Programmatic?
Which one is better and under what situation one should use it?
Can you give any proper examples or tutorial about it.
Also want to know that what is the latest things we should use while write database codes in spring?
What is the alternative for HibernateTemplate?
Programmatic Transaction Management
Allows us to manage transactions through programming in our source code.
This means hardcoding transaction logic between our business logic.
We use programming to manage transactions
Flexible, but difficult to maintain with large amount of business logic. Introduces boilerplate between business logic.
Preferred when relative less transaction logic is to be introduced.
Declarative Transaction Management
Allows us to manage transactions through configuration.
This means separating transaction logic with business logic.
We use annotations (Or XML files) to manage transactions.
Easy to maintain. Boilerplate is kept away from business logic.
Preferred when working with large amount of Transaction logic.
They are not mutually exclusive.
You can use decalrative transaction management (#Transactional) in most of cases, and fall back to programmatic transaction management (TransactionTemplate) when you face limitations of Spring AOP (see 11.5.1 Understanding the Spring Framework's declarative transaction implementation) or need to control transactions in more complex ways.
Spring offers both programmatic and declarative transactions.
Programmatic means you have transaction management code surrounding your business code.
This gives extreme flexibility, but is difficult to maintain and, well, boilerplate.
Declarative means you separate transaction management from the business code.
You can use annotations or XML based configuration.
programmatic management is more flexible during development time but less flexible during application life
declarative management is less flexible during development time but more flexible during application life
http://docs.spring.io/spring/docs/3.0.x/reference/transaction.html
Declarative Transaction Management allows to eliminate any dependencies on the transaction framework from the Java code. The four participants to provide the transaction support are transaction manager, proxy factory, transaction interceptor, and a set of transaction attributes.
Suggest to use Declarative Transaction Management, Alternative for HibernateTemplates either NamedJDBCTemplate or simpleJDBCTemplate
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html#tx-decl-vs-prog
and
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/transaction.html
in general.
examples:
http://www.springbyexample.org/examples/hibernate-transaction-annotation-config.html
New features: I suggest using DI with SessionFactory. Also take a look at 3.1 new feature: Hibernate 4 support. see http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/new-in-3.1.html#d0e1385
Programmatic transaction management is usually a good idea only if you have a small number of transactional operations. For example, if you have a web application that require transactions only for certain update operations, you may not want to set up transactional proxies using Spring or any other technology. In this case, using the TransactionTemplate may be a good approach. Being able to set the transaction name explicitly is also something that can only be done using the programmatic approach to transaction management.
On the other hand, if your application has numerous transactional operations, declarative transaction management is usually worthwhile. It keeps transaction management out of business logic, and is not difficult to configure.
There are two types of Transaction management that Spring supports:
1. Programmatic Transaction Management: Transaction is managed with the help of programming and provides extreme flexibility, but it is difficult to maintain.
2. Declarative Transaction Management: Transaction management is separated from business code and only annotations or XML based configurations are used to manage the transactions.

Transaction support in struts2

I am using struts2.0 for my project named online examination system.
I am using traditional JDBC approach in datya access layer. I can't use JPA.
I want to make entire service layer transactional, but i searched for the transaction support in struts2 but didn't get anything.
Although spring provides good support for making service layer transactional.
Please help me on this issue to find out transaction support in struts2.
You are on a wrong track here.Struts2 is only for MVC part and what you are doing at your service layer it has nothing to do with that.
If you want to take advantage of transaction API i suggest you to use either Spring AOP of if i am correct Google Guice also provides a way for AOP.
Whatever you use at your service layer for transaction handling Struts2 is independent of it and out of context

Springs Transaction Management - Understanding Spring Reference, Global/Local, Programmatic/Declarative - Two Questions

Im working with the Spring Framework 3.0.5 and the Hibernate Framework and Im starting to use now Springs Transactionmanagement. I have some questions, just to understand how Springs Transactionmanagement works.
1)
I read this things in the Spring reference:
a) Consistent programming model across different transaction APIs such as Java Transaction API (JTA), JDBC, Hibernate, Java Persistence API (JPA), and Java Data Objects (JDO).
b) Spring resolves the disadvantages of global and local transactions. It enables application developers to use a consistent programming model in any environment. You write your code once, and it can benefit from different transaction management strategies in different environments.
c) Gone are the days when the only alternative to using EJB CMT or JTA was to write code with local transactions such as those on JDBC connections, and face a hefty rework if you need that code to run within global, container-managed transactions. With the Spring Framework, only some of the bean definitions in your configuration file, rather than your code, need to change.
From a) I understand that I can use those APIs with Spring without changing the code
From b) I understand that I can use global or local transactions *without changing the code
From c) I understand that while switching between different APIs and global/local transactions I need to change the code
Now I wonder what is correct?
=> Do I need to change the code? When switching between different APIs? When switching between local and global transactions? (Or does it maybe depend on prorgammatic and declarative transaction management?)
2)
I also got an additional question: I really wonder what the use of programmatic transaction management is? Everywhere I read that declarative transactionmanagement is recommended
I read this in spring reference too:
d) With programmatic transaction management, developers work with the Spring Framework transaction abstraction, which can run over any underlying transaction infrastructure. With the preferred declarative model, developers typically write little or no code related to transaction management, and hence do not depend on the Spring Framework transaction API, or any other transaction API.
From d) I understand: with programmatic transaction management I can use any underlying transaction infrastructure... which means what? the different APIs mentioned above?
and: with declarative I do not depend on any api
=> isnt this the same? when I can use any underlying api, I do not depend on any api. I do not really understand this.
where is the difference? I only know that the declarative transaction management is more lightweight, that I have not to start the transaction by my self and catch the exception and handle it and so on. But what is the use of programmatic transaction management then?
Thank you for answering! :-)
You're over-thinking this a bit. The Spring API provides an abstract transaction model that has the same API and semantics regardless of which underlying transaction technology you use. In order to switch from one technology to another, you generally have to alter your Spring config, but the idea is that you never needs to to alter your business logic. So whether you're using local, in-VM JDBC transactions or fully distributed, two-phase-commit XA JPA-style transactions, the API usage within your Spring code is the same. Only the configuration changes.
The difference between declarative and programmatic transaction management is that with the former, you use annotations or XML config to say which bits of code are supposed to be transactional. With programmatic style, you specifically enclose transactional logic using method calls into the Spring API. Note that if you use the declarative style, then Spring will wrap your code in generated logic which uses the programmatic style. The latter is simply a more explicit and low-level version of the former. It gives you more control, but it's more verbose.

Resources