EJB,Hibernate and spring transaction - spring

I've a question regarding the use of the transaction manager in a context with EJB, Spring and Hibernate.
In our project we have an EJB stateless marked with the annotation #TransactionAttribute(TransactionAttributeType.REQUIRED).
No further transaction has been defined so far.
Now every EJB calls a service. The latter is only a delegates the redirect the call to the final DAO. In every DAO we use the HibernateTemplate: the problem is that the session is closed soon after every get/load methods inside the DAOs. Why?
If I replace the HibernateTemplate with the classic Hibernate Session (best approach) and I call getSession().getTransaction().isActive() I get always false, but the session is still active 'till the end of the service call (the delegates mentioned above). After this the session closed.
Why do I have this different behaviours?
Isn't Spring/hibernate able to see the EJB transaction attribute?
Thanks in advance.
Fabio

Related

Does spring-data by default always use the same persistence context within the same request?

An example is if my spring controller has two Autowired services, and both services have a PersistenceContext also controled by spring (and i'm doing nothing more), will both share the same context in every request by default?
No, they will use different ones. A persistence context (EntityManager) is defined to be a thread-bound concept in JPA. Thus each request will see a fresh instance of EntityManager for each new request.
For a singleton Spring component that gets an EntityManager injected, Spring will autowire you a proxy instance so that it can easily exchange the backing instance. This a core Spring container feature and doesn't need anything in Spring Data JPA (see the documentation here).

Spring JPA and Sharing Entity Manager across multiple WARS and #Persistence Context thread safety

I read about about Persistence Context but not able to get a clear picture about my doubts which are as follows.
1. I have a DAO class which as a #PersistenceContext(unitName="") private EntityManager entityManager and from my Service method i am starting the transaction(Spring Managed) using #Transactional(propagation = Propagation.REQUIRED). I understand here is every time this Service method is called, a Transaction will start and when it reaches to DAO class it will use the same Transaction but for every EntityManager operation it look for Active PersistenceContext and create it as required. Is this approach correct and thread safe?
So, if a new thread starts the same service method then a new Transaction and a persistence Context will be created and flushed away when the method ends?
2. I have multiple WARS which need to interact with database so I am sharing the EntityManagerFactory using Spring Shared contexts. I am having all the Hibernate related configurations at a common place and in every WAR i am specifying where transactionManager will be shared. Is it right?
Please clarify my doubts and your comments are valued. Thanks in advance.

Spring MVC controller initialization code

I have a spring MVC project, in one of the controllers, i have a DB connection object that needs to be initialized only once in the controller, what is the best approach to follow when adding this initialization code, for now, i used a static block in the controller where i added the initialization code, do u have any other suggestions.
thanks in advance
Make it a Spring bean. That way it's a singleton (by default), and can be injected wherever you want.
Note that even if you leave its initialization in the controller, making it static is useless, since a controller is also a Spring bean, which is a singleton by default.
Well in spring you don't need to initialize the db connections yourself , It provide support for db connections
You just need to specify the the bean in .xml files and directly autowired that bean into your controller
use dao pattern to implement database connections see some example it will be easy container will manage db connections object life cycle for you
Thanks,
Himanshu
May I recommend you read the Spring reference guide for Object Relational Mapping and Data Access? Its quite comprehensive and details how to set up a data source, session factory, implement DAO classes, transaction management etc... Hopefully you will find this is a good place to start.

EJB 3.0 , are thread safe?

Hy,
I am a newbie in EJB. Now I am studying the EJB 3.0 specification. If I have two different JSF managed beans like the next ones:
#ManagedBean
public class CocheBean {
#EJB
private ICochesService cochesService = null;
}
#ManagedBean
public class UsuarioBean {
#EJB
private ICochesService cochesService = null;
}
The injecteds implementations for cochesService are the same in both cases?, I mean, for each annotation, the ejb container gets back a new object or is the same object?
Why do they refer to EJBs as session beans? Are they session scoped? Do they exist till the session of a user expires?
Its said that you dont have to worry if the stateless EJB are thread safe because the container has a pool of different instances for each request but if they are stateless and there is no danger that multiple threads access to just one ejb, why the container creates a pool of them and not just one?
Using JSF managed beans, if this bean is request or session scoped and because we inject the ejbs in this beans, they cannot be called more than once per user or per request at the same time, right?
How to specify the transactional atributes to EJB bean methods, with JPA annotations?
Thanks
This depends - if ICochesService is stateless than each of them will have different object. If it's stateful or singleton than both beans will have the same object injected
Answer to both questions is no :) See the Oracle docs
Exactly
You can call as many beans as you want per each request.
See the Oracle tutorial for Java Transaction API.

Spring: Why the SessionFactoryUtils class in Hibernate 4 does not provide the getSession method?

What happened to the SessionFactoryUtils.getSession method from Hibernate 4 in Spring 3.1.0 ? What should be used instead ? sessionFactory.getCurrentSession() keeps giving me this exception:
org.hibernate.HibernateException: No Session found for current thread
at org.springframework.orm.hibernate4.SpringSessionContext.currentSession(SpringSessionContext.java:97)
at org.hibernate.internal.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:883)
Any hint ?
Use sessionFactory.getCurrentSession()
I believe the concept of a "current session" came in Hibernate 3, SessionFactoryUtil was written before this existed.
Not sure why did they remove it, probably they implemented a better design using org.hibernate.context.CurrentSessionContext. As from this post:
... Simply use the plain SessionFactory and use the getCurrentSession
method to obtain the current transactional session (don't use
openSession!!!!) and you are good to go...
As from documentation of SessionFactory.getCurrentSession():
The definition of what exactly "current" means controlled by the CurrentSessionContext impl configured for use.
You have to add a property example:
<prop key="hibernate.current_session_context_class">thread</prop>
to your session factory bean mapping. (check the hibernate documentation for more details)
The 'org.hibernate.HibernateException: No Session found for current thread' exception happens when you haven't configured your transaction demarcation properly with Spring.
Typically, Spring opens a session for you when your transaction starts, binds it to a ThreadLocal and re-uses it for the duration of your transaction. When your transaction commits, the session is closed (after it was flushed). So, you don't need to make any calls to the SessionFactory class yourself.
Usually, people put #Transactional on a class (typically a Service) and configure Spring to start and end transactions on method invocations on that class.

Resources