Apr 28, 2010

How To Use Transaction Manager with @Transactional without getting 'org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here' Exception?

Its you readers who post comments on my blog often induce me to post more information and additional write ups here!I sincerely thank you for that induction you create in me! Based on the information requested, I thought of posting an article here that would help many of you (like me) who end up with the very famous "org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here".

If you are looking at the procedure to incorporate the TxManager in your spring application by making use of @Transactional annotation along with org.springframework.orm.hibernate3.HibernateTransactionManager and , here is the right information that you can make use of! This would not only help you to get out of 'org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here' exception but would also help you in understanding the rudiments involved with the transaction very easily.

Here are the basic steps that you can make use of. Let us say that you have an applicationContect.xml(This is the application context that is loaded by the contextLoaderListener/contextLoaderServlet of your application). Let us say that you have a webdispatcherservlet's webapplication context named as application-servlet.xml.

In this case, please follow the steps given below to incorporate the transactions with ease. In my opinion, it is always recommended that you have your service layer transactional . So i intend introducing the @Transactional annotations at the services in the following example!
  1. First and foremost, define the TxManager bean within the applicationContext.xml as shown below. Remember that this context is the place where you should define the component scan for the services and daos present within your application.
  2. <bean id="transactionManager"
    class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="defaultSessionFactory" />
    </bean>
    
    <tx:annotation-driven transaction-manager="transactionManager" />
  3. Note that if you define the bean id of your TxManager as transactionManager, the tx:annotation driven tag can be as given below. It literally means that you need not define the name of your transaction manager in the tx:annotation-driven tag. If you have this bean's id as something else other than "transactionManager", you need to have the the additional attribute "transaction-manager" to the tx:annotation-driven tag.
  4. <tx:annotation-driven /><br />
  5. Next,define the xmlns for the tx tag as given below in the same applicationContext.xml
  6. xmlns:tx="http://www.springframework.org/schema/tx"<br />
  7. Further, you need to add the schema location for the Tx tag as shown below in the same applicationContext.xml
  8. http://www.springframework.org/schema/tx <br />http://www.springframework.org/schema/tx/spring-tx-3.0.xsd<br />
  9. Next, go to your daoImpl file say sampleDaoImpl.java and define the sessionFactory as shown below
  10. @Repository("SampleDAO")<br />public class SampleDaoImpl implements SampleDao {<br /><br />    @Autowired<br />    @Qualifier("appSessionFactory")<br />    private SessionFactory sessionFactory;<br />
  11. Remember that you have to use the sessionFactory injected in your daoimpl as shown below
  12. sessionFactory.getCurrentSession().saveOrUpdate(hibernateObject);<br />
    or
    sessionFactory.getCurrentSession().createSQLQuery("<your query here>")<br />
  13. Next, go to your service impl layer. Let us say that you have your service implementation file named as SampleServiceImpl.java. Here, you will have to introduce the @Transactional annotations. Be careful and ensure that you make the transaction read only for the find and get queries while you can make the transaction writeable in methods that updates, saves or deletes the objects in db as follows. Here, you can make the @Transactional annotation at class level as read only. When you have an update method that writes to the db, you can annotate that method with @Transactional(readOnly=false) for this would override the class level annotation incorporated as readonly!
  14. @Service("sampleServiceImpl")<br />@Transactional(readOnly = true)<br />public class SampleServiceImpl implements SampleService {<br />@Autowired<br />@Qualifier("sampleDAO")<br />private SampleDAO sampleDAO;<br />public sampleObject getObject(int id)<br />{<br />return sampleDao.getObject(id);<br />}<br />@Transactional(readOnly = false)<br />public void update(SampleObject sampleObj) <br />{<br />sampleDAO.saveOrUpdate(sampleObj);<br />}<br />}<br />
  15. That is it!!!Your application would have included the TxManager successfully! Your db calls would be then managed by the Spring defined TxManager without any problems from here!
While this depicts a very simple implementation, you can go ahead and change the properties for the @Transctional annotation further to modify the propagation and isolation levels wherever necessary! You can also implement multiple transactional managers if need be by using @Transactional("TxManager1") and @Transactional("TxManager2") and by defining the corresponding TxManagers in your appplicationContext.xml with ease!!! Hope this helps you to circumvent the famous "org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here"! Whatsoever, keep me posted and stay tuned!

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Apr 27, 2010

Field versus Property Access in Hibernate :Understanding @AccessType in Hibernate

Programming with POJOs is emphatically a part and parcel of hibernate! But deciding the contents and the property access within the POJOs is at the discretion of the programmer. However, from a procedural programmer's perspective, the instant answer to such a scenario would be to opt for getters and setters for the properties within the POJOs! Before we have a look at whether this is really right and recommended, the other important consideration would be the accesstype! This can either be field or property level. Nonetheless, the controversies regarding the usage of Property or filed level access for the properties in the POJOs still continues and dosent seem to end even till date!

What is @Accesstype in Hibernate?

Let us say that you have a POJO as follows. The location of annotating the id property of the POJO with @Id and @column annotations in hibernate determines the access level of this domain object
public class Sample {
private int id;
private String title;
private String Description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return Description;
}
public void setDescription(String description) {
Description = description;
}
}

Type 1: Field Access with @Accesstype in Hibernate

In the above POJO, if we annotate he id property as follows, then we are offering field level access to the properties inside the POJO. ORM framework chooses to access the fields using Introspection and reflection rather than via the getters and setters.
@Entity <br />public class Sample {<br />    @Id<br />    @Column(name = "id", nullable = false)<br />    private int id;<br />    <br />    @Column(name = "title", nullable = false)<br />    private String title;<br />    <br />    @Column(name = "description", nullable = false)<br />    private String Description;<br />    <br />}<br /><br />
In this case, getters and setters are not necessary! Such coding supports future changes to the structure of the domain object with ease. It not only offers clean/maintainable code but also better encapsulation, though a procedureal programmer would emphatically deny such a statement!And for those, who argue that having accessor methods offers better encapsulation, I would suggest to go through this article for that would better explain the nuances very clearly!

In future, if there is a need for AOP integration or business logic incorporation within the domain objects, then that can be very well supported by adding the necessary behaviour to this POJO as and when needed!


Type 2: Property Access with @Accesstype in Hibernate

But, if we annotate the properties on top of the getter methods, then it is that the POJO uses property elvel access. It is as given below:
@Entity <br />public class Sample {<br />    private int id;<br />    private String title;<br />    private String Description;<br />    <br />    @Id<br />    @Column(name = "id", nullable = false)<br />    public int getId() {<br />        return id;<br />    }<br />    public void setId(int id) {<br />        this.id = id;<br />    }<br />    @Column(name = "title", nullable = false)<br />    public String getTitle() {<br />        return title;<br />    }<br />    public void setTitle(String title) {<br />        this.title = title;<br />    }<br />    @Column(name = "description", nullable = false)<br />    public String getDescription() {<br />        return Description;<br />    }<br />    public void setDescription(String description) {<br />        Description = description;<br />    }<br />}<br />

Such access of domain objects via getters/setters is again another way of accessing the properties of the POJO. The ORM framework uses accessors to set and get properties in this case. If in case, there is a need for business validations to be incorporated at a later date, then there might be a need for additional set of getters and setters that might have to be implemented in code. This not only makes the coding cluttered but also makes the maintenance burdensome!

Mix up!

This is always possible! You can have the default field access and mark the properties that need the proeprty level access as transient. Further, you can define the annotation for such properties before their accessors
@Entity <br />public class Sample {<br />    @Id<br />    @Column(name = "id", nullable = false)<br />    private int id;<br />    @Transient <br />    private String title;<br />    @Transient <br />    private String Description;<br />    <br />   <br />    @Column(name = "title", nullable = false)<br />    public String getTitle() {<br />        return title;<br />    }<br />    public void setTitle(String title) {<br />        this.title = title;<br />    }<br />    @Column(name = "description", nullable = false)<br />    public String getDescription() {<br />        return Description;<br />    }<br />    public void setDescription(String description) {<br />        Description = description;<br />    }<br />}<br />

Existing Controversies

With respect to performance, it can be vouched that there is not much of difference between the two methods discussed above. However, While a survey by google vouches that the field access is preferred, there is still another face to this issue that needs to be analysed in depth!

As per the @AccessType implementation of hibernate, if we intend to get the identifier of an associated object in hibernate, if we use property level access, then hibernate understands that there is getId() method in the corresponding POJO and hence gets the id without initializing the proxy. However, this does not work if we use filed level access. If we intend to get the id of the associated object, since there is property level access defined, hibernate does not knoww about the accessor methods in this domain object and hence tries to initilaize the proxy to get the id of the associated object!As a result, Hibernate team strongly suggests the use of property access if we do not want the proxy initialization to happen since that might result in lazy initialization exception if done out side the session.

Yet another temporary solution has been discussed in this link. However, a note with title @org.hibernate.annotations.AccessType in hibernate documentation

The annotation @org.hibernate.annotations.AccessType should be considered deprecated for FIELD and PROPERTY access. It is still useful however if you need to use a custom access type.

Adding fuel to this fire is the bug reported in hibernate. While this points to the proxy initialization issue on calling getId() of an embedded object within hibernate, it is very clear that Property level access is being discouraged by Hibernate (though Spring's dictum is to opt for field level access only as in this link.

Best Practices

  1. There is not much of difference between the field and property level access with respect to performance.
  2. Field level access would be preferred if the code avoids hibernate proxy pitfalls!If there is a need for property access later, this can always be supported by adding the necessary accessors!
  3. Field level access proves to be good if you really want the annotations closer to the code. This not only gives a fare idea of the property details but also avoids unnecessary accessors that might prove to be great evil. Additionally, having accessors is emphatically not a good OO design strategy!
  4. If you are using filed level access, remember that Hibernate would initialize the proxy on getting the id of an associated object at least until the bug gets resolved.
  5. Property level access can be implemented as long as you do not have business logic or validations within your domain objects since one such scenario can prove to be very dangerous! The positive aspect about this type of access is that Hibernate does not initialize the proxy in case of getting the identifier of the associated POJO.
  6. Overall, the usage of field and property level access depends much on the requirement as the first consideration and then the coding style!

If you find the information pretty pretty helpful, I would really be happy if you would keep me posted! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Apr 23, 2010

How To Solve org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here?

When we implemented transactions using autowiring and TxManager in the spring config xml file, we ended up in having the well known org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here.

I was googling a bit on "No Hibernate Session bound to thread". Emphatically, I ended up with innumerous answers in several sites on the Internet. Springsource forum is not exception to this! Abundant conversations have been happening on this topic all around!!!

But there were a few best practices that I was able to compile from the chit-chats happening across the Internet. I thought of sharing the same here so that it would help some one some day in the near future!

  1. First and foremost, configure the transaction manager properly : Use @Transaction annotation near your code and have a transactionManager bean in your spring config file.
  2. when integration a transaction manager, do not use hibernate.current_session_context_class and hibernate.transaction_factory_class in the hibernate properties unless you have proper reasons to
  3. Never call sessionFactory.openSession()
  4. Use ApplicationContext rather than using BeanFactory
  5. Have single dao instances running across the Application
  6. Above all, most importantly, ensure that the current application context has the component scan for the beans where you have added the @transactional annotations. as per spring documentation's @ Trasactional usage guidelines,

<tx:annotation-driven/> only looks for @Transactional on beans in the same application context it is defined in. This means that, if you put <tx:annotation-driven/> in a WebApplicationContext for a DispatcherServlet, it only checks for @Transactional beans in your controllers, and not your services. See Section 15.2, “The DispatcherServlet” for more information.

Point # 6 was the culprit in our case and that was then resolved! So the lessson was You are likely to get "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" if you do not adhere to any of the above pointers.
PArticularly, if you are going to have the applicationContext.xml with the TxManager and the servletname-servlet.xml with the component scan annotations, then you are more likely to get this "No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here" exception since the TxManager's transaction holds good for the current application context only (which in this case does not have the bean definitions for the service or the daos where you have the @ Trasactional annotations)

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Resolve java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor

Spring 3.0 is emphatically remarkable! When we moved to Spring 3.0, everything worked fine and the team was of course happy! While doing this, we were also trying to move transactions from the old-school way (using hibernate.cfg.xml) to autowiring session factory and making it annotation driven! The latter move forced us to introduce the following code in out applicationContext.xml
<tx:annotation-driven transaction-manager="transactionManager" />


When we thought everything would work, we were surprised to see that on deployment, tomcat reported:
<br />java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor<br />

While this Resolve java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor kept us in surprise, I had to google around a bit! On searching a bit across the Internet, I came across the following solution

Solution:

The previous versions of Spring (<3.0)were shipping AOPAlliance.jar which was required to run the above annotation. In spring 3.0 however, does not come bundles with this jar. As such, if you use Spring 3.0, it is important that you download this jar from this link

Yet another utile pointer that I came across is the fact that there is a JIRA issue to include the AOPAlliance.jar in future releases of Spring! Once I added this jar to the classpath of my application, the Resolve java.lang.NoClassDefFoundError: org/aopalliance/intercept/MethodInterceptor error disappeared!

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!

Spring Integration with Hibernate

I was working on a nice web application that was using Spring, Hibernate, jquery and Apache velocity! The saddest fact was the reality that Spring was not properly integrated into Hibernate and transactions were not properly handled.

At last, after a detailed discussion on what would happen if such an application goes live, the spring has been integrated properly with Hibernate! As soon as one starts integrating Hibernate with Spring, the various options would be
  1. To use HibernateTemplate
  2. To use HibernateDaoSupport
  3. Use plain Hibernate with hibernate.cfg.xml (like what we have been using till date)
  4. Autowire session factory as a bean in the daos
The Pros and Cons
  1. Using HibernateTemplate
  2. HibernateTemplate is a nice API from Spring for easy integration with hibernate. It mirrors all methods exposed to Hibernate session and proves to be handy! Automatic session close and transaction participation proves to be the best part of this API. Additionally this is handy not only for the nice exception translation but also helps a newbie who does not want to handle sessions or transactions by himself. But, with the advent of Hibernate 3.0.1, this API (using HibernateTemplate.find and the like  - This includes defining private HibernateTemplate in the daos and setting the hibernate template while setting the session factory in a setter method say setSessionFactory) just proves to be futile and it is highly recommended that it is better to handle the sessionFactory by ourselves rather than clinging to Spring and depending on it for handling the sessions for us! As such, this proves to be the first level of Spring and Hibernate integration and is a good option for a newbie!
  3. Using HibernateDaoSupport
  4. The process of writing SampleDaoImpl extends HibernateDaoSupport is not doubt a very good option. Here, we would then be using no callbacks and session  = getSession(false) rather than setting the hibernate template via the session factory. This is emphatically a very remarkable API provided by Spring for integration with hibernate and is surely better than the option 1 discussed above since this allows throwing of checked exception within the data access code.
  5. Using plain Hibernate with hibernate.cfg.xml
  6. While this proves to be the mos traditional way of implementation, this is just for the hibernate fans. I am not for such an implementation since there is no need for writing code as given below:
    Session session = HibernateUtils.getSession();
    try{
    Transaction tx = session.beginTransaction();
    session.save(Object o);//o is the incoming object to be persisted
    tx.commit();
    }
    catch{
    (Exception e)
    //code to handle exception
    }
    finally{
    session.close();
    
    
  7. Using Autowiring of the SessionFactory
  8. As far as i see, this is the best way of integrating spring with hibernate. This is not only the latest and the updated way of integration, this proves to be the best solution for designing web application where the developer has a hold on the sessions and transactions though Spring does this in its own way
    <br /><br /><?xml version="1.0" encoding="utf-8"?><br /><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"<br />xmlns:context="http://www.springframework.org/schema/context" xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"<br />xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"><br /><br /><!-- Auto-detection of the DAOs --><br />    <context:component-scan base-package="webapp.dao" /><br />    <context:property-placeholder location="WEB-INF/jdbc.properties" /><br /><!--<context:property-override location="WEB-INF/override.properties"/>--><br />    <br />    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.url}"<br />    p:username="${jdbc.username}" p:password="${jdbc.password}" p:maxActive="${dbcp.maxActive}" p:maxIdle="${dbcp.maxIdle}" p:maxWait="${dbcp.maxWait}" /><br />    <br />    <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean" p:dataSource-ref="dataSource"<br />    p:configurationClass="org.hibernate.cfg.AnnotationConfiguration" p:packagesToScan="webapp.model"><br />        <property name="hibernateProperties"><br />            <props><br />                <prop key="hibernate.dialect">${hibernate.dialect}</prop><br />                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop><br />                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop><br />                <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop><br />            </props><br />        </property><br />       <br />    </bean><br />    <br /> <tx:annotation-driven transaction-manager="txnManager"/> <br /> <bean id="txnManager"<br />        class="org.springframework.orm.hibernate3.HibernateTransactionManager"<br />        p:sessionFactory-ref="sessionFactory"/><br /><br /></beans><br />
    The corresponding DAO class is as below
    @Repository<br />@Transactional<br />public class SampleDaoImpl implements SampleDao {<br /><br />  @Autowired<br />  SessionFactory sessionFactory;<br />

If you find the information pretty helpful, I would really be happy if you would keep me posted via the comments form displayed under this article! If you had wanted some other information related to the same topic, I would suggest you to drop a note to me using the comments form for that would help me in getting back to you with the details you are in need of!