Spring MVC - Distributed Database Transaction - java

I'm currently developing a web application using Spring MVC (without Maven).
What I need is to create a distributed transaction between two local databases, so that the code will update all of them in (theoretically) a 2phase commit.
Now, since I'm doing it for a school project, I'm in a simple environment which needs only to take a row from a table in one db and put it in a table on the other db, of course atomically (theoretically, such a transaction should be distributed because I'm using two different databases and not only one).
My question is, how can I deploy a Spring bean that firstly connects to both MySQL databases and then does that distributed transaction? Should I use some external library or could I achieve all with only using the Spring framework? In which case, could you please kindly link me an example or a guide to do this?
Thank you in advance for your help :)

Spring has an interface PlatformTransactionManager which is an
abstraction And it has many implementations like
DataSourceTransactionManager,HibernateTransactionManager etc.
Since you are using distributed transactions so you need to use
JTATransactionManager
These TransactionManagers provided by spring
are wrapper around the implementations provided by other frameworks
Now in case of JTA , you would be using either an application server
or a standalone JTA implementation like Atomikos
Following are the steps :-
Configure Transaction Manager in spring using application server
or standalone JTA implementation
Enable Transaction Management in spring
And then configure in your code the #Transactional annotation above
your method
Have a look at following links
http://docs.spring.io/spring/docs/current/spring-framework-reference/html/transaction.html
http://www.byteslounge.com/tutorials/spring-jta-multiple-resource-transactions-in-tomcat-with-atomikos-example

Related

How Spring Boot Application to listen for a CRUD operations

I am just starting with Spring boot Web Applications, and I am in this point now I need to issue notification in the app ecosystem after CRUD Operation in database (I am using MySQL)
How can I set up a listener and based on the operation to create a new notification. From my search, I land on #EntityListeners(AuditTrailListener.class) but not sure how to use it, I will be happy to share with me some examples or to redirect me to the right place to see how to set up that kind of listener.
Here's a collection of links which are providing some details about #EntityListeners with JPA in Spring Boot webapplications :
JPA Entity Lifecycle Events
A gist of a php-coder
Spring Data JPA Entity Auditing using EntityListeners
Spring JPA Auditing in Official Documentation
StackOverflow: How to use an #Autowired #EntityListener
StackOverflow: How to inject a dependency into a JPA #EntityListener
I think you'll have common paths to seek the information you need with all that links. And maybe other people will help you more.

Change Java Spring Boot Bean while runtime

Hello fellow developers,
i created a library using the Spring boot framework.
This library is creating a dynamic database connection using #Beans where i create a "data" Bean which holds the unlimited Datasource beans provided by a Postgresql db. At the end i wanted to have a dynamic db connection which could be triggered from outside to change the db i want to connect to. The information of the different databases where stored as mentioned inside of a postgres. This is loaded at the application start into this bean. My Problem is, that i'm not able to switch between the different Datasource beans. Spring boot is creating them, but it seems like it's not possible to change the bean started at runtime of the application which only holds one of the unlimited Datasources... So also after a retriggering of the creation of the original bean it still uses the old datasource.
Is there a way to use the beans from spring boot and change them on runtime?
Regards,
Andreas
I believe you are asking for DB multitenancy support where tenants information is stored in a Postgres DB.
Configuring the persistent layer for multi-tenancy support involves configuring:
Hibernate, JPA and Datasources properties
Datasources beans
Entity manager factory bean
Transaction manager bean
Spring Data JPA and annotation-driven transactions
I recently blog about Multi-tenant applications using Spring Boot, JPA, Hibernate and Postgres and although the tenants data is stored in a yml "properties" file, it shouldn't be difficult to convert it to read tenant data from a DB. I think it would be a starting point for what you would like to accomplish.

Spring Boot and Spring Data application with multiple DataSources created in runtime

I am developing a Spring Boot application that uses Spring Data JPA and will need to connect to many different databases e.g. PostreSQL, MySQL, MS-SQL, MongoDB.
I need to create all datasources in runtime i.e. user choose these data by GUI in started application:
-driver(one of the list),
-source,
-port,
-username,
-password.
And after all he writes native sql to choosen database and get results.
I read a lot of things about it in stack and spring forums(e.g. AbstractRoutingDataSource) but all of these tutorials show how to create datasources from xml configuration or static definition in java bean. It is possible to create many datsources in runtime? How to manage transactions and how to create many sessionFactories? It is possible to use #Transactional annotation? What is the best method to do this? Can someone explain me how to do this 'step by step'?
Hope it's not too late for an answer ;)
I developed a module which can be easily integrated in any spring project. It uses a meta-datasource to hold the tenant-datasource connection details.
For the tenant-datasource an AbstractRoutingDataSource is used.
Here you find my core implementation using the AbstractRoutingDataSource.
https://github.com/Dactabird/multitenancy
Here is an example to show how to integrate it. https://github.com/Dactabird/multitenancy-sample
In this example I'm using H2 embedded db. But of course you can use whatever you want.
Feel free to modify it for your purposes or to ask if questions are left!

How can I use JDBCTemplate from Spring JDBC in a Swing desktop application?

I use a lot of JDBC code in my Swing desktop application. Now I read about JDBCTemplate from Spring in Spring in Action and it looks like a nice API for working with JDBC.
But Spring JDBC seem to need some XML configuration files for beans. Is there any way I can use JDBCTemplate without these XML configuration files (e.g. with annotations)? Or how can I use this JdbcTemplate in a Swing desktop application for database access?
You can have a Spring Context without XML by creating a #Configuration anotated java class and create the Spring Context using the AnnotationConfigApplicationContext class to load the config
see Spring JavaConfig for a code sample.
While using Spring as the backbone of your application certainly has merit, and indeed annotation-based configuration can free you from 'XML hell', if you just want to use JdbcTemplate 'raw' there's nothing preventing you from doing so.
Just make sure you supply it with a valid DataSource, such as PGPoolingDataSource for example, if you're using PostgreSQL. If your JDBC vendor does not provide a DataSource implementation, then feel free to use Spring's SimpleDriverDataSource.
For example:
DataSource ds = new SimpleDriverDataSource(LegacyDriver.class,
"jdbc:legacy://database", "username", "password");
JdbcTemplate jdbc = new JdbcTemplate(ds);
// Use jdbc to do stuff
Even though its technically possible - it would defeat the purpose and design of Spring based application.
My suggestion would be to start using Spring framework as a backbone for you application. I promise you that your application will only benefit from using it (better design, clear separation of concerns, better testability etc ). Setting up JbdcTemplate using Spring context is almost trivial.
You already reading 'Spring in Action' - just start using it :)
Take a look at Spring Reference Documentation - the best Spring resource, period

How do I write an application that more or less acts as a container?

I am planning an application that must provide services that are very much like those of a Java EE container to third party extension code. Basically, what this app does is find a set of work items (currently, the plan is to use Hibernate) and dispatch them to work item consumers.
The work item consumers load the item details, invoke third party extension code, and then if the third party code did not fail, update some state on the work item and commit all work done.
I am explicitly not writing this as a Java EE application. Essentially, my application must provide many of the services of a container, however; it must provide transaction management, connection pooling and management, and a certain amount of deployment support. How do I either A) provide these directly, or B) choose a third party library to provide them. Due to a requirement of the larger project, the extension writers will be using Hibernate, if that makes any difference.
It's worth noting that, of all of the features I've mentioned, the one I know least about is transaction management. How can I provide this service to extension code running in my container?
Hi I recommend using the Spring Framework. It provides a nice way to bring together a lot of the various services you are talking about.
For instance to address your specific needs:
Transaction Management/Connection pooling
I built a spring-based stand-alone application that used Apache commons connection pooling. Also I believe spring has some kind of transaction mgmt built in.
Deployment support
I use ant to deploy and run things as a front-loader. It works pretty well. I just fork a seperate process using ant to run my Spring stand-alone app.
Threading.
Spring has support for Quartz which deals well with threads and thread pools
DAO
Spring integrates nicely with Hibernate and other similar projects
Configuration
Using its xml property definitions -- Spring is pretty good for multiple-environment configuration.
Spring does have transaction management. You can define a DataSource in your application context using Apache DBCP (using a org.apache.commons.dbcp.BasicDataSourceorg.springframework.jdbc.datasource.DataSourceTransactionManager for the DataSource. After that, any object in your application can define its own transactions programatically if you pass it the TransactionManager, or you can use AOP interceptors on the object's definition in your application context, to define which methods need to be run inside a transaction.
Or, the easier approach nowadays with Spring is to use the #Transactional annotation in any method that needs to be run inside a transaction, and to add something like this to your application context (assuming your transactionManager is named txManager):
<tx:annotation-driven transaction-manager="txManager"/>
This way your application will easily accept new components later on, which can have transaction management simply by using the #Transactional annotation or by directly creating transactions through a PlatformTransactionManager that they will receive through a setter (so you can pass it when you define the object in your app context).
You could try Atomikos TransactionsEssentials for Java transaction management and connection pooling (JDBC+JMS) in a J2SE environment. No need for any appservers, and it is much more fun to work with ;-)
HTH
Guy

Categories