I have no development experience with Spring, since we're a Java EE shop. However, we are looking into a solution for our needs that runs on Spring and should integrate our existing Java EE solution.
After reading the Spring 3.0.5 documentation, I'm still uncertain how a transaction can be propagated from Spring to an EJB.
For instance, a Spring bean would create a transaction, save some stuff into one database and then hand over the transaction to one of our stateless session beans, which (using JPA) saves some other stuff into another database. And all of this must run under the same transaction, which is committed when the control is returned to the Spring bean.
Also, I'm not clear about the deployment: Would Spring run as a webapp in the EAR that contains the session beans?
if you configure Spring to use a JTATransactionManager and then call your SessionBean from within Spring the bean should actually pick up the Spring-created transaction. Have look here: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#transaction-application-server-integration and the described <tx:jta-transaction-manager/>
I actually only did it the other way around (joining EJB Transaction in spring) so I'm not completely sure, but you can easily test it by setting
#TransactionAttribute(TransactionAttributeType.MANDATORY)
on your SessionBean and call it from spring... if there's not existing Transaction you will end up with a TransactionRequiredException
Related
I am trying to learn Spring Framework, before that I used to create application with EJBs
[Web services]->[Business Layer]->[DAO Layer] | [Database]
in following way
WebServices: Restful API using Jersey with url mappings, that support both JSON and XML format( news/list.json, news/list.xml). Once a request is received by an endpoint(url-mapped-method) it is forwarded to a relevant EJB through lookup(remote, local). EJB process every thing, apply business rules and return result as DTO(Data transfer object),Service then transform the result into required format (JSON, XML)
Business Layer: Business Layer (Facade) implemented in EJB with remote and local interfaces, these EJBs can call other EJBs. WebService layer(and/or Timer service and MDBs) can also call any of the EJBs). For timer service related functionality I used EJB Timer Service and for Messages used Message Drive Bean and interceptor for logging and auditing.
DAO Layer: All the Database related functions(add,edit, delete, search) JPA/Hibernate using EntityManager are written here (Entity beans and HQL).
Seamless Transaction support, each EJB's method (lookup-based) call is treated as a separate transaction and calling methods of DAO layer are part of same transaction(provided that no extra configuration is provided). multiple operations are carried out in a single transaction If one db operation fails all others are roll backed automatically. Each Table is mapped as an entity class with relations etc.
I have worked on Spring MVC but could not map/understand correctly for above architecture
I know bit about AOP and that I think is a perfect replacement for Interceptors (or at least it work for me)
Now my question is how all these could be replaced in Spring framework?
Jersey (RestAPi) alternative in Spring>
EJB alternative in Spring (as EJB supports remoting, each lookup call to a method is treated as a transaction, calls to EJB's method could be intercepted and it comes with state-full and stateless flavors)?
Timer Service alternative in Spring?
Message Drive Bean alternative in Spring?
Interceptor alternative is AOP in Spring (As per my experience and that serve my purpose)
JPA(entity manager) alternative in spring?
Jersey (RestAPi) alternative in Spring?
Spring MVC does this perfectly fine, in my opinion. Just annotate your methods in your controller as the REST apis you want to use.
EJB alternative in Spring (as EJB supports remoting, each lookup call to a method is treated as a transaction, calls to EJB's method could be intercepted and it comes with state-full and stateless flavors)?
There is no full alternative. There are several techniques that implement this in parts: Spring remoting for remote calls, Spring transactions as transactions, Spring AOP interceptors for intercepting calls. However, for example XA transactions on remote calls are something you don't get as such in Spring. Spring however works fine with EJBs, so if you prefer them, you can still have them and use Spring in other parts of your software.
Timer Service alternative in Spring?
Spring task scheduling
Message Drive Bean alternative in Spring?
Message Listener Containers
Interceptor alternative is AOP in Spring (As per my experience and that serve my purpose)
There are several levels of interceptors in spring. There are handler interceptors in mvc, there are bean call interceptors like the SpringAutowiringInterceptor, and there are AOP-based interceptors that can be used in multiple layers.
JPA(entity manager) alternative in spring?
Spring has multiple of these as well. It's actually quite straightforward to just use JPA with Spring-Data, it's designed to integrate to JPA. There are Spring JDBC and other data layer alternatives though if Spring Data is not what you want.
Jersey (RestAPi) alternative in Spring ⇨ it's rest api (in spring with #Path annotation) or spring mvc if you want to use controllers (#Controller annotation)!
EJB alternative in Spring ⇨ Spring doesn't give statefull bean out of a box but you can use #Service annotation (or #Repository for DAO) but you have to handle transactions manually (with annotations for example)
Message Drive Bean alternative ⇨ There is no equivalent out of the box in Spring, you could use injection and librairies of Spring to get it working (package org.springframework.jms should contains what you need)!
JPA(entity manager) alternative is not ejb ⇨ so it can be used in Spring.
Spring is a lighweight library so you can do all you do with EJB but it's more configurable so you will have more work to do the same that EJB do. But this configuration brings you some advantages: you have the hand on it!
This explains Spring and Java EE (which is what you would have used EJBs in) side by side: http://www.slideshare.net/reza_rahman/java-ee-and-spring-sidebyside-34320697
Jersey offers Spring solutions too - see their website
Spring does support remote calls through, e.g., RMI; It also supports transactions; AFAIK, no explicit stateful/stateless Spring Components - it depends on how you use it
AFAIK nothing as awesome as TimerService, however, you could use Quartz
Spring offers MDPs (Message-Driven POJOs)
Spring does support JPA - see first link.
Another cool comparison slideshare: http://www.slideshare.net/kelapure/java-e-evsspringshootout
I have some confusion on using JTA within the Spring Framework on Apache Tomcat and i hope someone will clarify as after many research i can't seem to find the correct answer as of yet.
I am developing a web application using Spring Framework to be running on Apache Tomcat 6.
I read somewhere that Spring's does support for JTA but it delegates to the underlying JavaEE application server. Now this is where i am confused because i Tomcat is not a full JavaEE application server - it is merely a servlet container and as i believe it doesn't provide JTA implementation like the full JavaEE application server (Glassfish/Wildfly etc...) does.
But when i do something like the following the transaction aspect of it works:
#Transactional
public class ServiceClassImpl implements ServiceInterface {
// code here that involves transactions e.g. calling DAO code
...
}
So, i'm confused. I hope someone will enlighten me.
The answer is: NO.
Tomcat 6.x (7&8) don't provide JTA out-of-the-box because they don't have a transaction manager which is required as a separate component to monitor multiple resources (e.g. datasources).
The mentioned answer How to use JTA support in Tomcat 6 for Hibernate? already gives a list of additional JTA transaction managers that can be used alongside Tomcat.
Spring supports declarative transaction management via a platform transaction manager (TM) and provides some implementations (e.g. datasources) that make #Transactional work on a single resource without the additional TM.
Understanding the Spring Framework transaction abstraction provides more details and Spring Boot can be easily configured to run Atomikos or Bitronix Transaction managers on the embedded Tomcat.
JTA provides you with distributed transactions support, but if JTA is not available like in Tomcat, you still can use local JDBC transactions.
YES :-)
JTA can be used in Tomcat, for instance via https://www.atomikos.com
The trick is to use a componentized JTA implementation.
Cheers
I have some doubts on container managed transaction, as per my knowledge container managed transaction is one where container takes care of transactions i.e commit and rollback.
What is container? Is it EJB or App server?
If I want to do CMT with hibernate how do Iachieve this? I have tried using app server JTA but when I open session in hibernate it says no transaction found.
If I use App server JTA implementation what kind of transaction is it?
Do I have to make use of EJB to have CMT?
EJB is a container, a container like EJB can be part of an App server.
Try to find some tutorials, there are many of them available. Here an tutorial for EJB on JBoss: http://www.mastertheboss.com/jboss-frameworks/hibernate-jpa/quickstart-tutorials-hibernate-jpa
Sry, i don't understand the question.
CMT is an ejb concept, but you could use the transaction management from spring => have a look at this if you are interested in spring transaction management: http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/transaction.html
Just try some simple tutorials => for example google for ejb hibernate tutorial => after some practice you will find out how it works :)
I'm just getting started with JPA, creating stateless session beans from the JPA entities, then accessing the beans through a web service. While I have a lot of experience developing database backed web services "the old way", I have some questions about what's going on behind the scenes with this new "annotation driven approach".
What I see is, NetBeans sort of directs you to build applications in this manner though their wizards.
Create an Enterprise Application with EJB and Web Application modules.
Create Entity classes. I created mine from an existing database.
Create session beans from the entity class.
Create Web services from the session bean.
It all looks pretty simple, but what's going on behind the scenes? Specifically:
I see that the web service (created with the #WebService annotation) references my stateless session bean (using the #EJB reference).
What happens here? Does it just grab an instance of the EJB from the application server's EJB pool?
Nevermind. I was thinking of an instance where there was more than 1 table - meaning more than 1 type of Entity class and more than 1 type of EJB. I was looking at the web service and just seeing the #EJB reference and didn't understand who it was getting the bean type from that annotation. Just below that however, it the reference to the local bean interface - so that's that.
If there is more than 1 type of EJB deployed to the server, how does it know which one to grab?
The EJB is defined via the #Stateless and #Local annotations. The bean implementation references an EnityManager via the #PersistenceContext annotation.
Where is the jndi lookup to the database done (maybe in the persistence.xml file)?
Do all of the EJBs share a common EntityManager (assuming the EntityManager is thread safe)? If not, I know that the EnityManager utilizes a second level cache to help reduce trips to the database, are these caches somehow kept in sync?
I know this is a lot of questions, but they're all sort of related and there seem to be a lot of complicated concepts for something that's so easy to build through the wizards. I want to make sure I understand what's all going on here.
Thanks in advance!
What happens here? Does it just grab an instance of the EJB from the application server's EJB pool?
A JAX-WS web component endpoint (as opposed to a JAX-WS EJB endpoint) follows the typical servlet threading model, which means that typically there is one instance that is executed concurrently for each client. JAX-WS implementations are free to leverage pools of bean instances to handle a request in a fashion similar to stateless session EJB components. (source: Developing Applications for the JavaTM EE Platform FJ-310).
In all cases, it is fine to inject/look-up stateless beans because the container guarantees that the beans will always be thread safe. In affect, the container automatically serializes clients calls but uses instance pooling to make sure you still get concurrency benefits.
If there is more than 1 EJB deployed to the server, how does it know which one to grab?
Hmm... I didn't get this one. Can you clarify what you mean exactly? Why would there be any ambiguity?
Where is the jndi lookup to the database done (maybe in the persistence.xml file)?
In a Java EE environment, you specify your data source in a <jta-data-source> element in each persistence unit of the persistence.xml file (which can contain several persistence units) and the data source will be obtained by the EntityManager (only when needed, i.e. only if a data access is really needed).
Do all of the EJBs share a common EntityManager?
No. The EntityManager is a non-thread-safe object that should be used once, for a single business process, a single unit of work, and then discarded. In a Java EE environment using EJB 3, the default pattern is "entitymanager-per-request". A request from the client is send to the EJB 3 persistence layer, a new EntityManager is opened, and all database operations are executed in this unit of work. Once the work has been completed (and the response for the client has been prepared), the persistence context is flushed and closed, as well as the entity manager object. (source: Chapter 4. Transactions and Concurrency).
What role is Spring taking in Struts + Spring + Hibernate?
Spring provides many different "modules" and different programmers will use different parts of Spring.
However, commonly in this sort of stack, you will see Spring being used as a provider of
An inversion of control container for dependency injection
An abstraction to Hibernate called "HibernateTemplate"
Framework classes for simplifying Aspect Oriented Programming
Transaction support, often "declaratively" via the IoC container and AOP.
Well, Hibernate handles the persistence part, JSP handles your GUI, Struts controls the flow between pages/actions/etc, and Spring can manage all your beans which contain the main business logic, instead of using EJB. Plus it can simplify the coding of your Hibernate DAO's and transaction managing.
Instead of having to code your Locator to obtain some EJB through JNDI and all that stuff, you can just get the Spring ApplicationContext and ask for the bean you need. All the beans defined in Spring can be interconnected. If you have to connect one of your beans to an external EJB through JNDI you can even do so without any code (Spring offers a JNDI proxy object which obtains the reference you give it and returns it as an object with the interface you specify). This can help you simplify unit testing of all those beans and change the config without recoding anything; you can use one of Spring's PlatformTransactionManagers to manage a DataSource or point it to a J2EE container's JTA manager; define your own pooled DataSource or use your container's DataSource published through JNDI, etc.
Well to add;
(Views and Controllers) Struts for its extensive JSP features with Struts tags and web request handling features
(Service and application management) Spring to handle the ORM and service layers with its excellent dependency injections,etc.
(ORM with db independence) Hibernate for well proven ORM