Original Address:On the annotation inheritance problem of transaction
Author:Anders
Because in DAO is used: session instead of Hibernatetemplate
Let's talk about the difference between hibernatetemplate and session.
There's no big difference in how you use it.
One of the important reasons we use hibernatetemplate is that we don't want to directly control the transaction, do not want to get it directly, open the session, start a transaction, handle the exception, commit a transaction, Finally close a sessionhibernatetemplate is hibernate operation to encapsulate, we only need simple bar with Hibernatetemplate object, pass in hql and parameter, get query interface, as for transaction open, close, are handed over to the Hibernatetemplate object to handle our own focus on the business and do not want to do these repetitive and tedious operations. We entrust all of these responsibilities to hibernatetemplate and then use declarative configuration to implement such a function. If we get the session through a method like getsession (), it means that we give up all the benefits mentioned above.
So there's no business in session ()
This requires your own manual configuration of the transaction, which is configured on the service layer
So in the config file Appluicationcontext:
<bean id= "TX" class= "Org.springframework.orm.hibernate3.HibernateTransactionManager" >
<property name= "Sessionfactory" ref= "Sessionfactory" ></property>
</bean>
<!--declares the use of transactions as annotations ... -
<tx:annotation-driven transaction-manager= "TX"/
The declaration declares the transaction in the form of annotations.
As a base class for writing a Baseserviceimpl
So each service is inherited with Baseserviceimpl
In the Baseserviceimpl
@Transactional
public class baseserviceimpl<t, E extends ibasedao<t>> implements Ibaseservice<t, e> {
In the Employeeserviceimpl
@Service
public class Employeeserviceimpl extends Baseserviceimpl<employee, iemployeedao> implements Iemployeeservice {
This shows that only in Baseserviceimp have l@transactional
(the case says @transactiona should be added in each service)
That's why.
Because: annotation can be inherited, it must be added in the base class @transactional
If you add @transactional to the service only
While the base class does not add
(i.e.
public class baseserviceimpl<t, E extends ibasedao<t>> implements Ibaseservice<t, e> {
In the Employeeserviceimpl
@Service
@Transactional
public class Employeeserviceimpl extends Baseserviceimpl<employee, iemployeedao> implements Iemployeeservice {
)
There will be the following exception
Org.hibernate.HibernateException:No hibernate Session bound to thread, and configuration does not allow creation of NON-T Ransactional one Her
This is because the subclass service calls the method of the parent class, and the methods in the parent class are not @transactional
So there will be an exception ...