February 3, 2011

Part 10: Initializing MyBatis on Application Startup

If you've been following Part 9 of this tutorial, we now need to make sure our application has an sqlSessionVariable available ready to go when the TestServlet is invoked.

I had recently written a more detailed article about how to initialize MyBatis when a web application starts up. You can read that here.

For this part of the tutorial, I'm just going to summarize what you need to do to get MyBatis to automatically initialize when the ModelingAgency webapp starts.

Setting up a ServletContextListener

A ServletContextListener is useful when you want to do something when a java application starts up, more specifically, when a ServletContext is initalized.

In our case, we're going to use a ServletContextListener to set a MyBatis SqlSessionan application scoped varible. This will allow us to instantiate our ModelingAgencyDAO object from our TestServlet. Here's how to do it:

1) Register the listener in web.xml

Add the following code to web.xml


2) Create the Listener class

Create the class CustomServletContextListener.java under the com.modelingagency.listeners package:

package com.modelingagency.listeners;
import java.io.Reader;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
public class CustomServletContextListener implements ServletContextListener
 public void contextInitialized(ServletContextEvent event)
  ServletContext ctx = event.getServletContext(); 
     String resource = "mybatis.config.xml";
      Reader reader = Resources.getResourceAsReader(resource);     
      SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); //this will load the default environment configured in mybatis.config.xml
      ctx.setAttribute("sqlSessionFactory", sqlSessionFactory); //set the sqlSessionFactory as an application scoped variable
     catch(Exception e){
      System.out.println("FATAL ERROR: myBatis could not be initialized");
 public void contextDestroyed(ServletContextEvent event){
   //nothing to do here right now

If everything went well so far, you should be able to run the application again. Going to http://localhost:8080/ModelingAgency/test.do however will show the same things as before. So we need to finalize our interface.

Part 11: Finalizing the Interface