Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Tutorial: Linked/Cascading ExtJS Combo Boxes using Spring MVC 3 and Hibernate 3.5

DZone's Guide to

Tutorial: Linked/Cascading ExtJS Combo Boxes using Spring MVC 3 and Hibernate 3.5

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

This post will walk you through how to implement ExtJS linked/cascading/nested combo boxes using Spring MVC 3 and Hibernate 3.5. I am going to use the classic linked combo boxes: state and cities. In this example, I am going to use States and Cities from Brazil! ;)

What is our main goal? When we select a state from the first combo box, the application will load the second combo box with the cities that belong to the selected state.

There are two ways to implement it.

The first one is to load all the information you need for both combo boxes, and when user selects a state, the application will filter the cities combo box according to the selected state.

The second one is to load information only to populate the state combo box. When user selects a state, the application will retrieve all the cities that belong to the selected state from database.

Which one is best? It depends on the amount of data you have to retrieve from your database. For example: you have a combo box that lists all the countries in the world. And the second combo box represents all the cities in the world. In this case, scenario number 2 is the best option, because you will have to retrieve a large amount of data from the database.

Ok. Let’s get into the code. I’ll show how to implement both scenarios.

First, let me explain a little bit of how the project is organized:

Let’s take a look at the Java code.

BaseDAO:

Contains the hibernate template used for CityDAO and StateDAO.

package com.loiane.dao;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;

@Repository
public abstract class BaseDAO {

	private HibernateTemplate hibernateTemplate;

	public HibernateTemplate getHibernateTemplate() {
		return hibernateTemplate;
	}

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		hibernateTemplate = new HibernateTemplate(sessionFactory);
	}
}
CityDAO:

Contains two methods: one to retrieve all cities from database (used in scenario #1), and one method to retrieve all the cities that belong to a state (used in scenario #2).

package com.loiane.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.loiane.model.City;

@Repository
public class CityDAO extends BaseDAO{

	public List<City> getCityListByState(int stateId) {

		DetachedCriteria criteria = DetachedCriteria.forClass(City.class);
		criteria.add(Restrictions.eq("stateId", stateId));

		return this.getHibernateTemplate().findByCriteria(criteria);

	}

	public List<City> getCityList() {

		DetachedCriteria criteria = DetachedCriteria.forClass(City.class);

		return this.getHibernateTemplate().findByCriteria(criteria);

	}
}

 

StateDAO:

Contains only one method to retrieve all the states from database.

package com.loiane.dao;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.springframework.stereotype.Repository;

import com.loiane.model.State;

@Repository
public class StateDAO extends BaseDAO{

	public List<State> getStateList() {

		DetachedCriteria criteria = DetachedCriteria.forClass(State.class);

		return this.getHibernateTemplate().findByCriteria(criteria);

	}
}

City:

Represents the City POJO, represents the City table.

package com.loiane.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.codehaus.jackson.annotate.JsonAutoDetect;

@JsonAutoDetect
@Entity
@Table(name="CITY")
public class City {

	private int id;
	private int stateId;
	private String name;

	//getters and setters
}

State:

Represents the State POJO, represents the State table.

package com.loiane.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.codehaus.jackson.annotate.JsonAutoDetect;

@JsonAutoDetect
@Entity
@Table(name="STATE")
public class State {

	private int id;
	private int countryId;
	private String code;
	private String name;

	//getters and setters
}

CityService:

Contains two methods: one to retrieve all cities from database (used in scenario #1), and one method to retrieve all the cities that belong to a state (used in scenario #2). Only makes a call to CityDAO class.

package com.loiane.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.loiane.dao.CityDAO;
import com.loiane.model.City;

@Service
public class CityService {

	private CityDAO cityDAO;

	public List<City> getCityListByState(int stateId) {
		return cityDAO.getCityListByState(stateId);
	}

	public List<City> getCityList() {
		return cityDAO.getCityList();
	}

	@Autowired
	public void setCityDAO(CityDAO cityDAO) {
		this.cityDAO = cityDAO;
	}
}

StateService:

Contains only one method to retrieve all the states from database. Makes a call to StateDAO.

package com.loiane.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.loiane.dao.StateDAO;
import com.loiane.model.State;

@Service
public class StateService {

	private StateDAO stateDAO;

	public List<State> getStateList() {
		return stateDAO.getStateList();
	}

	@Autowired
	public void setStateDAO(StateDAO stateDAO) {
		this.stateDAO = stateDAO;
	}
}

CityController:

Contains two methods: one to retrieve all cities from database (used in scenario #1), and one method to retrieve all the cities that belong to a state (used in scenario #2). Only makes a call to CityService class. Both methods return a JSON object that looks like this:

{"data":[
         {"stateId":1,"name":"Acrelândia","id":1},
         {"stateId":1,"name":"Assis Brasil","id":2},
         {"stateId":1,"name":"Brasiléia","id":3},
         {"stateId":1,"name":"Bujari","id":4},
         {"stateId":1,"name":"Capixaba","id":5},
         {"stateId":1,"name":"Cruzeiro do Sul","id":6},
         {"stateId":1,"name":"Epitaciolândia","id":7},
         {"stateId":1,"name":"Feijó","id":8},
         {"stateId":1,"name":"Jordão","id":9},
         {"stateId":1,"name":"Mâncio Lima","id":10},
]}

Class:

package com.loiane.web;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.loiane.service.CityService;

@Controller
@RequestMapping(value="/city")
public class CityController {

	private CityService cityService;

	@RequestMapping(value="/getCitiesByState.action")
	public @ResponseBody Map<String,? extends Object> getCitiesByState(@RequestParam int stateId) throws Exception {

		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		try{

			modelMap.put("data", cityService.getCityListByState(stateId));

			return modelMap;

		} catch (Exception e) {

			e.printStackTrace();

			modelMap.put("success", false);

			return modelMap;
		}
	}

	@RequestMapping(value="/getAllCities.action")
	public @ResponseBody Map<String,? extends Object> getAllCities() throws Exception {

		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		try{

			modelMap.put("data", cityService.getCityList());

			return modelMap;

		} catch (Exception e) {

			e.printStackTrace();

			modelMap.put("success", false);

			return modelMap;
		}
	}

	@Autowired
	public void setCityService(CityService cityService) {
		this.cityService = cityService;
	}
}

StateController:

Contains only one method to retrieve all the states from database. Makes a call to StateService. The method returns a JSON object that looks like this:

{"data":[
         {"countryId":1,"name":"Acre","id":1,"code":"AC"},
         {"countryId":1,"name":"Alagoas","id":2,"code":"AL"},
         {"countryId":1,"name":"Amapá","id":3,"code":"AP"},
         {"countryId":1,"name":"Amazonas","id":4,"code":"AM"},
         {"countryId":1,"name":"Bahia","id":5,"code":"BA"},
         {"countryId":1,"name":"Ceará","id":6,"code":"CE"},
         {"countryId":1,"name":"Distrito Federal","id":7,"code":"DF"},
         {"countryId":1,"name":"Espírito Santo","id":8,"code":"ES"},
         {"countryId":1,"name":"Goiás","id":9,"code":"GO"},
         {"countryId":1,"name":"Maranhão","id":10,"code":"MA"},
         {"countryId":1,"name":"Mato Grosso","id":11,"code":"MT"},
         {"countryId":1,"name":"Mato Grosso do Sul","id":12,"code":"MS"},
         {"countryId":1,"name":"Minas Gerais","id":13,"code":"MG"},
         {"countryId":1,"name":"Pará","id":14,"code":"PA"},
]}

Class:

package com.loiane.web;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.loiane.service.StateService;

@Controller
@RequestMapping(value="/state")
public class StateController {

	private StateService stateService;

	@RequestMapping(value="/view.action")
	public @ResponseBody Map<String,? extends Object> view() throws Exception {

		Map<String,Object> modelMap = new HashMap<String,Object>(3);

		try{

			modelMap.put("data", stateService.getStateList());

			return modelMap;

		} catch (Exception e) {

			e.printStackTrace();

			modelMap.put("success", false);

			return modelMap;
		}
	}

	@Autowired
	public void setStateService(StateService stateService) {
		this.stateService = stateService;
	}
}

Inside the WebContent folder we have:

  • ext-3.2.1 – contains all ExtJS Files
  • js – contains all javascript files I implemented for this example. liked-comboboxes-local.js contains the combo boxes for  scenario #1; liked-comboboxes-remote.js contains the combo boxes for  scenario #2; linked-comboboxes.js contains a tab panel that contains both scenarios.

Now let’s take a look at the ExtJS code.

Scenario Number 1:

Retrieve all the data from database to populate both combo boxes. Will user filter on cities combo box.

liked-comboboxes-local.js

var localForm = new Ext.FormPanel({
      width: 400
      ,height: 300
      ,style:'margin:16px'
      ,bodyStyle:'padding:10px'
      ,title:'Linked Combos - Local Filtering'
      ,defaults: {xtype:'combo'}
      ,items:[{
           fieldLabel:'Select State'
          ,displayField:'name'
          ,valueField:'id'
          ,store: new Ext.data.JsonStore({
       		url: 'state/view.action',
            remoteSort: false,
            autoLoad:true,
            idProperty: 'id',
            root: 'data',
            totalProperty: 'total',
            fields: ['id','name']
        })
          ,triggerAction:'all'
          ,mode:'local'
          ,listeners:{select:{fn:function(combo, value) {
              var comboCity = Ext.getCmp('combo-city-local');
              comboCity.clearValue();
              comboCity.store.filter('stateId', combo.getValue());
              }}
          }

      },{
           fieldLabel:'Select City'
          ,displayField:'name'
          ,valueField:'id'
          ,id:'combo-city-local'
          ,store: new Ext.data.JsonStore({
      		   url: 'city/getAllCities.action',
              remoteSort: false,
              autoLoad:true,
              idProperty: 'id',
              root: 'data',
              totalProperty: 'total',
              fields: ['id','stateId','name']
          })
          ,triggerAction:'all'
          ,mode:'local'
          ,lastQuery:''
      }]
  });

The state combo box is declared on lines 9 to 28.

The city combo box is declared on lines 31 to 46.

Note that both stores are loaded when we load the page, as we can see in lines 15 and 38 (autoload:true).

The state combo box has select event listener that, when executed, filters the cities combo (the child combo) based on the currently selected state. You can see it on lines 23 to 28.

Cities combo has lastQuery:”". This is to fool internal combo filtering routines on the first page load. The cities combo just thinks that it has already been expanded once.

Scenario Number 2:

Retrieve all the state data from database to populate state combo. When user selects a state, application will retrieve from database only selected information.

liked-comboboxes-remote.js:

var dataBaseForm = new Ext.FormPanel({
       width: 400
       ,height: 200
       ,style:'margin:16px'
       ,bodyStyle:'padding:10px'
       ,title:'Linked Combos - Database'
       ,defaults: {xtype:'combo'}
       ,items:[{
            fieldLabel:'Select State'
           ,displayField:'name'
           ,valueField:'id'
           ,store: new Ext.data.JsonStore({
	       		url: 'state/view.action',
	            remoteSort: false,
	            autoLoad:true,
	            idProperty: 'id',
	            root: 'data',
	            totalProperty: 'total',
	            fields: ['id','name']
	        })
           ,triggerAction:'all'
           ,mode:'local'
           ,listeners: {
               select: {
                   fn:function(combo, value) {
                       var comboCity = Ext.getCmp('combo-city');
                       //set and disable cities
                       comboCity.setDisabled(true);
                       comboCity.setValue('');
                       comboCity.store.removeAll();
                       //reload city store and enable city combobox
                       comboCity.store.reload({
                           params: { stateId: combo.getValue() }
                       });
                       comboCity.setDisabled(false);
       			  }
               }
       		}
       },{
            fieldLabel:'Select City'
           ,displayField:'name'
           ,valueField:'id'
           ,disabled:true
           ,id:'combo-city'
           ,store: new Ext.data.JsonStore({
       		   url: 'city/getCitiesByState.action',
               remoteSort: false,
               idProperty: 'id',
               root: 'data',
               totalProperty: 'total',
               fields: ['id','stateId','name']
           })
           ,triggerAction:'all'
           ,mode:'local'
           ,lastQuery:''
       }]
});

The state combo box is declared on lines 9 to 38.

The city combo box is declared on lines 40 to 55.

Note that only state combo store is loaded when we load the page, as we can see at the line 15 (autoload:true).

The state combo box has the select event listener that, when executed, reloads the data for cities store (passes stateId as parameter) based on the currently selected state. You can see it on lines 24 to 38.

Cities combo has lastQuery:”". This is to fool internal combo filtering routines on the first page load. The cities combo just thinks that it has already been expanded once.

You can download the complete project from my GitHub repository:

I used Eclipse IDE + Tomcat 7 to develop this sample project.

References: http://www.sencha.com/learn/Tutorial:Linked_Combos_Tutorial_for_Ext_2

 

From http://loianegroner.com/2010/10/tutorial-linkedcascading-extjs-combo-boxes-using-spring-mvc-3-and-hibernate-3-5/

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}