In this post,  we are going to see java 8 Collectors examples. You can do various operations such as average, count, groupby, sort the list with the help of Collectors. I am not providing theory here, I think you will learn better with the help of examples.
Examples:

Counting:

Counting is used to count number of elements in the stream.It returns Collector instance which can be accepted by collect method.
package org.arpit.java2blog;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8CollectorsExample {

	public static void main(String[] args) {
		List<Integer> intList=Arrays.asList(10,20,30,40,50);
		// Counting
		long  count = intList.stream().collect(Collectors.counting());
		System.out.println(count);
		
	}
}
When you run above code, you will get below output:
5

AveragingInt :

AveragingInt is used to find average of stream elements as int datatype. It returns Collector instance which can be accepted by collect method.
package org.arpit.java2blog;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8CollectorsExample {

	public static void main(String[] args) {
		List<Integer> intList=Arrays.asList(10,20,30,40,50);
		// Averaging int
		Double result1 = intList.stream().collect(Collectors.averagingInt(v->v));
		System.out.println(result1);
		
		Double result2 = intList.stream().collect(Collectors.averagingInt(v->v*v));
		System.out.println(result2);
	}
}
When you run above code, you will get below output:
30.0
1100.0
Lets understand how did you get 30 for case 1 :
(10+20+30+40+50/5)= 150/5 =30.0 
Now you must wondering how did we get 1100 for 2nd case:
(10*10 + 20*20 + 30*30 + 40*40 + 50*50)/5=5500/5 = 1100.0 
If you want to understand more about v-> v*v , you can go through Java 8 lambda expressions Similarly we have different function for different data types such as AveragingDouble, AveragingLong.

joining

Joining method is used to concatenate with delimiter, you can also pass prefix and suffix.
package org.arpit.java2blog;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8CollectorsExample {

	public static void main(String[] args) {
		List<String> NameList=Arrays.asList("Arpit","John","Martin");
		// Counting
		String  stringWithHyphen = NameList.stream().collect(Collectors.joining("-"));
		System.out.println("String with hyphen : "+stringWithHyphen);
		String  stringWithHyphenAndPrefixAndSuffix = NameList.stream().collect(Collectors.joining("-","==","=="));
		System.out.println("String with hyphen , suffix and prefix :  "+stringWithHyphenAndPrefixAndSuffix);		
	}
}
When you run above code, you will get below output:
String with hyphen : Arpit-John-Martin
String with hyphen , suffix and prefix :  ==Arpit-John-Martin==

summingint:

summingInt is used to find sum of stream elements as int datatype. It returns Collector instance which can be accepted by collect method.
package org.arpit.java2blog;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8CollectorsExample {

	public static void main(String[] args) {
		List<Integer> intList=Arrays.asList(10,20,30,40,50);
		// Averaging int
		Double result1 = intList.stream().collect(Collectors.summingInt(v->v));
		System.out.println(result1);
		
		Double result2 = intList.stream().collect(Collectors.summingInt(v->v*v));
		System.out.println(result2);
	}
}
When you run above code, you will get below output:
150
5500
Similarly we have different function for different data types such as summingDouble, summingLong.

collectingAndThen:

collectingAndThen: is used to get a Collector instance and perform finishing function on top of it.
package org.arpit.java2blog;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Java8CollectorsExample {

	public static void main(String[] args) {
		List<Integer> intList=Arrays.asList(10,20,30,40,50);
		// collectingAndThen
		int result1 = intList.stream().collect(Collectors.collectingAndThen(Collectors.summingInt(v->(int)v),result->result/2));
		System.out.println(result1);
	}
}
When you run above code, you will get below output:
75
Reference: 
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html

Java 8 has made comparator more powerful using Lambda Expression. It has introduced many new APIs for Comparator. Lets go through some new feature of Comparator using Lambda expression.
Lets create a very simple class called Employee:
package org.arpit.java2blog;

public class Employee {

 private String employeeName;
 private int age;

 public Employee(String employeeName,int age)
 {
  this.employeeName=employeeName;
  this.age=age;

 }

 public String getEmployeeName() {
  return employeeName;
 }

 public void setEmployeeName(String employeeName) {
  this.employeeName= employeeName;
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public String toString()
 {
  return getEmployeeName()+" : "+getAge();
 }
}

Sort Employee list by name in classic way:

We will sort employee list in classic way
Collections.sort(employeeList,new Comparator<Employee>() {
   public int compare(Employee e1,Employee e2)
   {
    return e1.getName().compareTo(e2.getName());
   }
   
  });
Create EmployeeMain.java
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class EmployeeMain {

 public static void main(String[] args)
 {
  List<Employee> employeeList=getEmployees();
  System.out.println("Before Sorting: ");
  System.out.println(employeeList);
                // in classic way
  Collections.sort(employeeList,new Comparator<Employee>() {
   public int compare(Employee e1,Employee e2)
   {
    return e1.getName().compareTo(e2.getName());
   }
   
  });
                System.out.println("After Sorting: ");
                System.out.println(employeeList);
 }
 
 public static List<Employee> getEmployees()
 {
  List<Employee> employeesList=new ArrayList<Employee>();
  Employee e1=new Employee("John", 35);
  Employee e2=new Employee("Adam", 22);
  Employee e3=new Employee("Arpit", 28);
  Employee e4=new Employee("John", 30);
  Employee e5=new Employee("Grace", 38);
  Employee e6=new Employee("Arpit", 25);
  employeesList.add(e1);
  employeesList.add(e2);
  employeesList.add(e3);
  employeesList.add(e4);
  employeesList.add(e5);
  employeesList.add(e6);
  return employeesList;

 }
}

Run the above program and you will get following output:
Before Sorting: 
[John : 35, Adam : 22, Arpit : 28, John : 30, Grace : 38, Arpit : 25]
After Sorting: 
[Adam : 22, Arpit : 28, Arpit : 25, Grace : 38, John : 35, John : 30]

Sort Employee list by name using lambda expression:

We will sort Employee list by name using lambda expression, It will reduce complex Comparator syntax to simple line of code
Create EmployeeMain.java
package org.arpit.java2blog;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class EmployeeMain {

 public static void main(String[] args)
 {
  List<Employee> employeeList=getEmployees();
  System.out.println("Before Sorting: ");
  System.out.println(employeeList);
  // using lambda expression
  Collections.sort(employeeList,(Employee e1,Employee e2)->e1.getEmployeeName().compareTo(e2.getEmployeeName())); 
               System.out.println("After Sorting: "); 
          System.out.println(employeeList);
 }
 
 public static List<Employee> getEmployees()
 {
  List<Employee> employeesList=new ArrayList<Employee>();
  Employee e1=new Employee("John", 35);
  Employee e2=new Employee("Adam", 22);
  Employee e3=new Employee("Arpit", 28);
  Employee e4=new Employee("John", 30);
  Employee e5=new Employee("Grace", 38);
  Employee e6=new Employee("Arpit", 25);
  employeesList.add(e1);
  employeesList.add(e2);
  employeesList.add(e3);
  employeesList.add(e4);
  employeesList.add(e5);
  employeesList.add(e6);
  return employeesList;

 }
}

Run the above program and you will get following output:
Before Sorting: 
[John : 35, Adam : 22, Arpit : 28, John : 30, Grace : 38, Arpit : 25]
After Sorting: 
[Adam : 22, Arpit : 28, Arpit : 25, Grace : 38, John : 35, John : 30]]

Sort Employee list by name using lambda expression without type definitions:

Here we will not pass type definition to arguments in lambda expression.It will be interpreted in context
Just  change line no. 16 of Employee name from :
Collections.sort(employeeList,(Employee e1,Employee e2)->e1.getEmployeeName().compareTo(e2.getEmployeeName()));
To
Collections.sort(employeeList,(e1,e2)->e1.getEmployeeName().compareTo(e2.getEmployeeName()));
and Run EmployeeMain.java. You will get same output as above

Reverse sort:

JDK 8 has introduced a new help method for reverse sorting a list.
Change the main method in employee main to below method:
 public static void main(String[] args)
 {
  List<Employee> employeeList=getEmployees();
  System.out.println("Before Sorting: ");
  System.out.println(employeeList);
  // using lambda expression
  Collections.sort(employeeList,(Employee e1,Employee e2)->e1.getEmployeeName().compareTo(e2.getEmployeeName())); 
             System.out.println("After Sorting: ");  
               System.out.println(employeeList);
 }

In this post , we are going to see about Spring NamedParameterJdbcTemplate. In previous post, we have already seen Spring JdbcTemplate example. NamedParameterJdbcTemplate is used to pass named parameter instead of ? in case of JdbcTemplate.
It makes code more readable and maintainable. Lets say you have 10 parameters and you have to use 10 ? to represent parameters and pass it in same sequence in object[] array but with the help of NamedParameterJdbcTemplate, it is very easy to specify parameters.
Lets compare code for JdbcTemplate and NamedParameterJdbcTemplate :

JdbcTemplate :

public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (?,?,?)";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
  Object[] args = new Object[] { country.getId(), country.getCountryName(), country.getPopulation() };
  int status = jdbcTemplate.update(query, args);
  if (status != 0) {
   System.out.println("Country saved with country=" + country.getCountryName());
  } else
   System.out.println("Country save failed with country=" + country.getCountryName());
  return country;
 }

NamedParameterJdbcTemplate :

public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (:id,:countryname,:population)";
  Map<String,Object> namedParameters = new HashMap<String,Object> ();    
  namedParameters.put("id", country.getId());   
  namedParameters.put("countryname", country.getCountryName());
  namedParameters.put("population", country.getPopulation() );
  NamedParameterJdbcTemplate namedParamterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
  int status = namedParamterJdbcTemplate.update(query, namedParameters);
  if (status != 0) {
   System.out.println("Country saved with country=" + country.getCountryName());
  } else
   System.out.println("Country save failed with country=" + country.getCountryName());
  return country;
 }
As you can see, we have use :{paramterName} for passing paramters instead of ? .

Example: 

Lets understand with the help of simple example:
Create Country table in mysql database with following code:
CREATE TABLE COUNTRY
(
   id int PRIMARY KEY NOT NULL,
   countryName varchar(100) NOT NULL,
   population int NOT NULL
)
;
CREATE UNIQUE INDEX PRIMARY ON COUNTRY(id)
;
We will you use Country table for querying and updating values in database. Lets first create our bean class Country.java
package org.arpit.java2blog.model;

/*
 * This is our model class and it corresponds to Country table in database
 */

public class Country{
 
 int id;
 String countryName; 
 long population;
 
 public Country() {
  super();
 }
 public Country(int i, String countryName,long population) {
  super();
  this.id = i;
  this.countryName = countryName;
  this.population=population;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 }
 @Override
 public String toString() {
  return "Country [id=" + id + ", countryName=" + countryName + ", population=" + population + "]";
 } 
 
}
Create a DAO classed CountryDAO.java which will have all methods for database operations.
package org.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.model.Country;

public interface CountryDAO {
 
 List<Country> getAllCountries();

 Country getCountry(int id);
 
 Country addCountry(Country country);
 
 void updateCountry(Country country);
 
 void deleteCountry(int id);

}

Create DAO implementation of above interface using normal JDBC APIs.
package org.arpit.java2blog.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.arpit.java2blog.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository("countryDAONamedJDBC")
public class CoountryDAOImpl implements CountryDAO {

 @Autowired
 private DataSource dataSource;

 @Override
 public List<Country> getAllCountries() {
  String query = "select id, countryname, population from Country";
  List<Country> countryList = new ArrayList<Country>();
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

  List<Map<String, Object>> countryRows = jdbcTemplate.queryForList(query);

  for (Map<String, Object> countryRow : countryRows) {
   Country country = new Country();
   country.setId(Integer.parseInt(String.valueOf(countryRow.get("id"))));
   country.setCountryName(String.valueOf(countryRow.get("countryName")));
   country.setPopulation((Integer)countryRow.get("population"));
   countryList.add(country);
  }

  return countryList;
 }

 @Override
 public Country getCountry(int id) {
  String query = "select id,countryname, population from Country where id = :id";

  Map<String,Object> namedParameters = new HashMap<String,Object> ();   
  namedParameters.put("id", id);  
  NamedParameterJdbcTemplate namedParamterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
  // int status = namedParamterJdbcTemplate.update(query, namedParameters);

  // using RowMapper anonymous class, we can create a separate RowMapper
  // for reuse
  Country country = namedParamterJdbcTemplate.queryForObject(query, namedParameters, new RowMapper<Country>() {

   @Override
   public Country mapRow(ResultSet rs, int rowNum) throws SQLException {
    Country country = new Country();
    country.setId(rs.getInt("id"));
    country.setCountryName(rs.getString("countryname"));
    country.setPopulation(rs.getLong("population"));
    return country;
   }
  });

  return country;
 }

 @Override
 public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (:id,:countryname,:population)";
  Map<String,Object> namedParameters = new HashMap<String,Object> ();    
  namedParameters.put("id", country.getId());   
  namedParameters.put("countryname", country.getCountryName());
  namedParameters.put("population", country.getPopulation() );
  NamedParameterJdbcTemplate namedParamterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
  int status = namedParamterJdbcTemplate.update(query, namedParameters);
  if (status != 0) {
   System.out.println("Country saved with country=" + country.getCountryName());
  } else
   System.out.println("Country save failed with country=" + country.getCountryName());
  return country;
 }

 @Override
 public void updateCountry(Country country) {
  String query = "update Country set countryname=:countryname, population=:population where id=:id";
  Map<String,Object> namedParameters = new HashMap<String,Object> ();    
  namedParameters.put("id", country.getId());   
  namedParameters.put("countryname", country.getCountryName());
  namedParameters.put("population", country.getPopulation() );
  NamedParameterJdbcTemplate namedParamterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
  int status = namedParamterJdbcTemplate.update(query, namedParameters);
  if (status != 0) {
   System.out.println("Country updated with country=" + country.getCountryName());
  } else
   System.out.println("No Country found with country=" + country.getCountryName());
 }

 @Override
 public void deleteCountry(int id) {
  String query = "delete from Country where id=:id";
  Map<String,Object> namedParameters = new HashMap<String,Object> ();    
  namedParameters.put("id", id);  
  NamedParameterJdbcTemplate namedParamterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
  int status = namedParamterJdbcTemplate.update(query, namedParameters);
  if (status != 0) {
   System.out.println("Country deleted with id=" + id);
  } else
   System.out.println("No Country found with id=" + id);
 }

}

Create applicationcontext.xml as below
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

 <context:annotation-config />
 <beans:bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <beans:property name="url"
   value="jdbc:mysql://localhost:3306/CountryData" />
  <beans:property name="username" value="root" />
  <beans:property name="password" value="" />
 </beans:bean>
 <context:component-scan base-package="org.arpit.java2blog" />
</beans:beans>
Configure datasource basaed on your connection details, datasource bean will be autowired in CountryDAOImpl.
Create Main class named SpringApplicationMain.java as below
package org.arpit.java2blog.main;

import java.util.List;

import org.arpit.java2blog.dao.CountryDAO;
import org.arpit.java2blog.model.Country;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApplicationMain {
 public static void main(String[] args) {

  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  CountryDAO countryDao = (CountryDAO) context.getBean("countryDAONamedJDBC");

  Country countryUSA = new Country();
  countryUSA.setCountryName("USA");
  countryUSA.setPopulation(10000);
  
  Country countryIndia = new Country();
  countryIndia.setCountryName("India");
  countryIndia.setPopulation(20000);
  
  Country countryChina = new Country();
  countryChina.setCountryName("China");
  countryChina.setPopulation(30000);
  
  Country countryBhutan = new Country();
  countryBhutan.setCountryName("Bhutan");
  countryBhutan.setPopulation(5000);
  

  // Add Country
  countryDao.addCountry(countryUSA);
  countryDao.addCountry(countryIndia);
  countryDao.addCountry(countryChina);
  countryDao.addCountry(countryBhutan);
  // Read
  Country countryRead = countryDao.getCountry(3);
  System.out.println("Getting country with ID 3::" + countryRead.getCountryName());

  // Update
  countryRead.setPopulation(40000);
  countryDao.updateCountry(countryRead);

  // Get All
  List<Country> countryList = countryDao.getAllCountries();
  System.out.println(countryList);

  // Delete
  countryDao.deleteCountry(4);

  System.out.println("We are done with all operations");
 }
}
When you run above program, you will get below output:
Aug 28, 2016 11:01:20 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@71881149: startup date [Sun Aug 28 23:01:20 IST 2016]; root of context hierarchy
Aug 28, 2016 11:01:21 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Aug 28, 2016 11:01:21 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Country saved with country=USA
Country saved with country=India
Country saved with country=China
Country saved with country=Bhutan
Country Found::Country [id=3, countryName=China, population=30000]
Getting country with ID 3::China
Country updated with country=China
[Country [id=1, countryName=USA, population=10000], Country [id=2, countryName=India, population=20000], Country [id=3, countryName=China, population=40000], Country [id=4, countryName=Bhutan, population=5000]]
Country deleted with id=4
We are done with all operations

In this post, we are going to see Spring JdbcTemplate example.
Spring jdbcTemplate is used to convenient way to connect to database and execute queries. It internally use JDBC code only, but provides you APIs , so you don't have to write boiler plate code. You don't have write much code before and after executing queries for creating connection , creating statement , closing connections etc.

Lets understand with the help of simple example:

Lets say you want to save country object to database.
If you want to write it using normal JDBC api, you have to use below code:
 public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (?,?,?)";
  Connection con = null;
  PreparedStatement ps = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setInt(1, country.getId());
   ps.setString(2, country.getCountryName());
   ps.setLong(3, country.getPopulation());
   int out = ps.executeUpdate();
   if (out != 0) {
    System.out.println("Country saved with country=" + country.getCountryName());
   } else
    System.out.println("Country save failed with country=" + country.getCountryName());
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  return country;
 }
If you use Spring JdbcTemplate to do same operation, you need to use below code:
public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (?,?,?)";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
  Object[] args = new Object[] { country.getId(), country.getCountryName(), country.getPopulation() };
  int status = jdbcTemplate.update(query, args);
  if (status != 0) {
   System.out.println("Country saved with country=" + country.getCountryName());
  } else
   System.out.println("Country save failed with country=" + country.getCountryName());
  return country;
 }
If you observe above code, you can easily see that you need to write very less code with Spring JdbcTemplate and you also don't need to do exception handling

Spring example using Normal JDBC API: 

Create Country table in mysql database with following code:
CREATE TABLE COUNTRY
(
   id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
   countryName varchar(100) NOT NULL,
   population int NOT NULL
)
;

We will you use Country table for querying and updating values in database.

Lets first create our bean class Country.java
package org.arpit.java2blog.model;

/*
 * This is our model class and it corresponds to Country table in database
 */

public class Country{
 
 int id;
 String countryName; 
 long population;
 
 public Country() {
  super();
 }
 public Country(int i, String countryName,long population) {
  super();
  this.id = i;
  this.countryName = countryName;
  this.population=population;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 }
 @Override
 public String toString() {
  return "Country [id=" + id + ", countryName=" + countryName + ", population=" + population + "]";
 } 
 
}
Create a DAO classed CountryDAO.java which will have all methods for database operations.
package org.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.model.Country;

public interface CountryDAO {
 
 List<Country> getAllCountries();

 Country getCountry(int id);
 
 Country addCountry(Country country);
 
 void updateCountry(Country country);
 
 void deleteCountry(int id);

}

Create DAO implementation of above interface using normal JDBC APIs.
package org.arpit.java2blog.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.arpit.java2blog.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository("countryDAO")
public class CountryDAOImpl implements CountryDAO {

 @Autowired
 private DataSource dataSource;

 @Override
 public List<Country> getAllCountries() {
  String query = "select id, countryname, population from Country";
  List<Country> countryList = new ArrayList<Country>();
  Connection con = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   rs = ps.executeQuery();
   while (rs.next()) {
    Country country = new Country();
    country.setId(rs.getInt("id"));
    country.setCountryName(rs.getString("countryname"));
    country.setPopulation(rs.getLong("population"));
    countryList.add(country);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    rs.close();
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  return countryList;
 }

 @Override
 public Country getCountry(int id) {
  String query = "select countryname, population from Country where id = ?";
  Country country = null;
  Connection con = null;
  PreparedStatement ps = null;
  ResultSet rs = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setInt(1, id);
   rs = ps.executeQuery();
   if (rs.next()) {
    country = new Country();
    country.setId(id);
    country.setCountryName(rs.getString("countryname"));
    country.setPopulation(rs.getLong("population"));
    System.out.println("Country Found::" + country);
   } else {
    System.out.println("No Country found with id=" + id);
   }
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    rs.close();
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  return country;
 }

 @Override
 public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (?,?,?)";
  Connection con = null;
  PreparedStatement ps = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setInt(1, country.getId());
   ps.setString(2, country.getCountryName());
   ps.setLong(3, country.getPopulation());
   int out = ps.executeUpdate();
   if (out != 0) {
    System.out.println("Country saved with country=" + country.getCountryName());
   } else
    System.out.println("Country save failed with country=" + country.getCountryName());
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
  return country;
 }

 @Override
 public void updateCountry(Country country) {
  String query = "update Country set countryname=?, population=? where id=?";
  Connection con = null;
  PreparedStatement ps = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setString(1, country.getCountryName());
   ps.setLong(2, country.getPopulation());
   ps.setInt(3, country.getId());
   int out = ps.executeUpdate();
   if (out != 0) {
    System.out.println("Country updated with country=" + country.getCountryName());
   } else
    System.out.println("No Country found with country=" + country.getCountryName());
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }

 public void deleteCountry(int id) {
  String query = "delete from Country where id=?";
  Connection con = null;
  PreparedStatement ps = null;
  try {
   con = dataSource.getConnection();
   ps = con.prepareStatement(query);
   ps.setInt(1, id);
   int out = ps.executeUpdate();
   if (out != 0) {
    System.out.println("Country deleted with id=" + id);
   } else
    System.out.println("No Country found with id=" + id);
  } catch (SQLException e) {
   e.printStackTrace();
  } finally {
   try {
    ps.close();
    con.close();
   } catch (SQLException e) {
    e.printStackTrace();
   }
  }
 }
}

Create applicationcontext.xml as below
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
 xsi:schemaLocation="
  http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
  http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

 <context:annotation-config />
 <beans:bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <beans:property name="url"
   value="jdbc:mysql://localhost:3306/CountryData" />
  <beans:property name="username" value="root" />
  <beans:property name="password" value="" />
 </beans:bean>
 <context:component-scan base-package="org.arpit.java2blog" />
</beans:beans>
Configure datasource basaed on your connection details, datasource bean will be autowired in CountryDAOImpl.
Create Main class named SpringApplicationMain.java as below
package org.arpit.java2blog.main;

import java.util.List;

import org.arpit.java2blog.dao.CountryDAO;
import org.arpit.java2blog.model.Country;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringApplicationMain {
 public static void main(String[] args) {

  ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
  CountryDAO countryDao = (CountryDAO) context.getBean("countryDAO");

  Country countryUSA = new Country();
  countryUSA.setCountryName("USA");
  countryUSA.setPopulation(10000);
  
  Country countryIndia = new Country();
  countryIndia.setCountryName("India");
  countryIndia.setPopulation(20000);
  
  Country countryChina = new Country();
  countryChina.setCountryName("China");
  countryChina.setPopulation(30000);
  
  Country countryBhutan = new Country();
  countryBhutan.setCountryName("Bhutan");
  countryBhutan.setPopulation(5000);
  

  // Add Country
  countryDao.addCountry(countryUSA);
  countryDao.addCountry(countryIndia);
  countryDao.addCountry(countryChina);
  countryDao.addCountry(countryBhutan);
  // Read
  Country countryRead = countryDao.getCountry(3);
  System.out.println("Getting country with ID 3::" + countryRead.getCountryName());

  // Update
  countryRead.setPopulation(40000);
  countryDao.updateCountry(countryRead);

  // Get All
  List<Country> countryList = countryDao.getAllCountries();
  System.out.println(countryList);

  // Delete
  countryDao.deleteCountry(4);

  System.out.println("We are done with all operations");
 }
}
When you run above program, you will get below output:
Aug 28, 2016 11:01:20 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@71881149: startup date [Sun Aug 28 23:01:20 IST 2016]; root of context hierarchy
Aug 28, 2016 11:01:21 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationContext.xml]
Aug 28, 2016 11:01:21 PM org.springframework.jdbc.datasource.DriverManagerDataSource setDriverClassName
INFO: Loaded JDBC driver: com.mysql.jdbc.Driver
Country saved with country=USA
Country saved with country=India
Country saved with country=China
Country saved with country=Bhutan
Country Found::Country [id=3, countryName=China, population=30000]
Getting country with ID 3::China
Country updated with country=China
[Country [id=1, countryName=USA, population=10000], Country [id=2, countryName=India, population=20000], Country [id=3, countryName=China, population=40000], Country [id=4, countryName=Bhutan, population=5000]]
Country deleted with id=4
We are done with all operations

As you can see in CountryDAOImpl, you need write lot of code to handle connections, exceptions etc.

Spring JdbcTemplate example: 

Now Replaced above CountryDAOImpl.java with below Spring JdbcTemplate example.
package org.arpit.java2blog.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.arpit.java2blog.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository("countryDAO")
public class SpringJDBCTemplateExample implements CountryDAO {

 @Autowired
 private DataSource dataSource;

 @Override
 public List<Country> getAllCountries() {
  String query = "select id, countryname, population from Country";
  List<Country> countryList = new ArrayList<Country>();
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

  List<Map<String, Object>> countryRows = jdbcTemplate.queryForList(query);

  for (Map<String, Object> countryRow : countryRows) {
   Country country = new Country();
   country.setId(Integer.parseInt(String.valueOf(countryRow.get("id"))));
   country.setCountryName(String.valueOf(countryRow.get("countryName")));
   country.setPopulation((Integer)countryRow.get("population"));
   countryList.add(country);
  }

  return countryList;
 }

 @Override
 public Country getCountry(int id) {
  String query = "select id,countryname, population from Country where id = ?";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

  // using RowMapper anonymous class, we can create a separate RowMapper
  // for reuse
  Country country = jdbcTemplate.queryForObject(query, new Object[] {id}, new RowMapper<Country>() {

   @Override
   public Country mapRow(ResultSet rs, int rowNum) throws SQLException {
    Country country = new Country();
    country.setId(rs.getInt("id"));
    country.setCountryName(rs.getString("countryname"));
    country.setPopulation(rs.getLong("population"));
    return country;
   }
  });

  return country;
 }

 @Override
 public Country addCountry(Country country) {
  String query = "insert into Country (id, countryname, population) values (?,?,?)";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

  Object[] args = new Object[] { country.getId(), country.getCountryName(), country.getPopulation() };

  int status = jdbcTemplate.update(query, args);

  if (status != 0) {
   System.out.println("Country saved with country=" + country.getCountryName());
  } else
   System.out.println("Country save failed with country=" + country.getCountryName());

  return country;
 }

 @Override
 public void updateCountry(Country country) {
  String query = "update Country set countryname=?, population=? where id=?";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

  Object[] args = new Object[] { country.getId(), country.getCountryName(), country.getPopulation() };

  int status = jdbcTemplate.update(query, args);
  if (status != 0) {
   System.out.println("Country updated with country=" + country.getCountryName());
  } else
   System.out.println("No Country found with country=" + country.getCountryName());
 }

 @Override
 public void deleteCountry(int id) {
  String query = "delete from Country where id=?";
  JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

  int status = jdbcTemplate.update(query, id);
  if (status != 0) {
   System.out.println("Country deleted with id=" + id);
  } else
   System.out.println("No Country found with id=" + id);
 }

}
As you can see, you need to write very less code with SpringJdbcTemplate.
jdbcTemplate.update(query, args) : This method is used to add or update in database. Object[] args is arguments array corresponds to ? in the query. jdbcTemplate.queryForObject(query, new Object[] {id}, new RowMapper() : We have used RowMapper and overriden maprows method to set values from resultset to country object. When you run above SpringApplicationMain again , you will get similar ouput.

Lets compare lines of code for normal JDBC and Spring JdbcTemplate
Method
Total lines of code for same operations
JDBC API
170
Spring JdbcTemplate
106

In this post, we will see differences between get and load in hibernate. It is most asked interview question on hibernate.

Tutorial Content:

    Introduction to hibernate framework Hibernate hello world example in eclipse Difference between openSession and getCurrentSession Hibernate one to one mapping example Hibernate one to many mapping example Hibernate many to many mapping example Hibernate inheritance:Table per class hierarchy Hibernate inheritance:table per subclass Hibernate inheritance:Table per concrete class Difference between openSession and getCurrentSession Difference between get and load Spring MVC Hibernate MySQL CRUD example Spring Rest hibernate example
Before we actually see differences, let me give you brief introduction of both.

session.get()

  • session.get() method always hits database and returns actual object
  • It returns null in case it does not get object.

session.load()

  • session.load() method always does not hit database and returns proxy object
  • It throws  ObjectNotFoundException  in case it does not get object.

 get vs load in hibernate

Parameter
get
load
Database retrieval
It always hits the database
It does not hit database
If null
If it does not get the object with id, it returns null
If it does get the object with id, it throws ObjectNotFoundException
Proxy
It returns real object
It returns proxy object
Use
If you are not sure if object with id exists or not, you can use get
If you are sure about existence of object, you can use load

In this post,  we are going to see jQuery text method example.
text method is used to get text of all matched elements and text('new text') is used to set text for all matched elements. 
Syntax for text() :
$("selectors").text() 
Example :
$("div").text();
Syntax for text('new text') :
$("selectors").text('new text')
Example:
 $("div").text('this text is being set by text method');

Let's understand with the help of example:
<!doctype>
<html>
<head>
  <title>Jquery text method example </title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery text method example</h2>
<style>
.blackBorder{
        border:4px dotted black;
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#textButton").click(function(){
         alert($("div").text()) ;
      });
$("#setTextButton").click(function(){
         $("div").text('this text is being set by text() method');
      });
$("#reset").click(function(){
         location.reload();
   });
 });

</script>
<body>
  <button id="textButton">Using text</button>
  <button id="setTextButton">Using text('new text') </button>
<button id="reset">Reset</button>
<br />
<div class='blackBorder'>
 Hello world from java2blog!!!!
   </div>
<br/>
<div class='blackBorder' >
 Welcome to JQuery.
  </div>
</body>
</html>
Live demo: Jquery text method example on jsbin.com

In this post,  we are going to see jQuery prepend and prependTo methods.
Both do the same task, insert text or html before content of every selected elements, so it will put text or html to first index of selected element. Both methods add text or html as a child to selected elements .Syntax is quite different for for prepend and prepend to nethod. 
Syntax for prepend() :
$("selectors").prepend("element to be inserted")
Example :
$("div").prepend("<p class='red'>inserting using prepend</p>");
Syntax for prependTo() :
$("element to be inserted") .prependTo("div");
Example:
 $("<p class='blue'>inserting using prependTo </p>").prependTo("div");

Let's understand with the help of example:
<!doctype>
<html>
<head>
  <title>Jquery prepend and prependTo example </title>
  <script src="http://code.jquery.com/jquery-2.2.3.min.js"></script>
</head>
<h2>Jquery prepend and prependTo example</h2>
<style>
   .red{
        border:3px dotted red;
        color:red;
        font-family: arial narrow;
   }
 .blue{
        border:3px dotted red;
        color:blue;
        font-family: arial narrow;
   }
.blackBorder{
        border:4px dotted black;
</style>
<script type="text/javascript">
   $(document).ready(function(){
      $("#prependButton").click(function(){
         $("div").prepend("<p class='red'>inserting using prepend</p>");
      });
$("#prependToButton").click(function(){
         $("<p class='blue'>inserting using prependTo</p>").prependTo("div");
      });
$("#reset").click(function(){
         location.reload();
   });
 });

</script>
<body>
  <button id="prependButton">Using prepend</button>
  <button id="prependToButton">Using prependTo</button>
<button id="reset">Reset</button>
<div class='blackBorder'>
 Hello world from java2blog!!!!
   </div>
<br/>
<div class='blackBorder' >
 Welcome to JQuery.
  </div>
</body>
</html>
Live demo: JS Bin on jsbin.com

In this post , we will see how to do exceptional handling in Spring MVC using @ControllerAdvice. In previous post, we have already seen how to use @ExceptionHandler to handle exceptions but @ExceptionHandler can be applied to one controller only but what if you want to handle exception globally i.e. across multiple controller. You can use @ControllerAdvice to handle exceptions globally.
Lets understand this with the help of example:

1) Create a dynamic web project using maven in eclipse named "SpringMVCControllerAdviceExample"

Maven dependencies 

2) Our pom.xml will look like below
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.arpit.java2blog</groupId>
  <artifactId> SpringMVCControllerAdviceExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name> SpringMVCControllerAdviceExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
   <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
        </dependency>
 </dependencies>
 <build>
  <finalName> SpringMVCControllerAdviceExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>
</project>

Spring application configuration:

3) Change web.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>  
   <welcome-file>index.jsp</welcome-file>  
 
  </welcome-file-list>
 <servlet>
 <servlet-name>springrest</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>springrest</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>
4) create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <mvc:annotation-driven/>
<context:component-scan base-package="org.arpit.java2blog.controller" />
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
 <mvc:default-servlet-handler/>
</beans>

Create Controller 

6) Create a controller named "HelloWorldController.java" in package org.arpit.java2blog.controller
package org.arpit.java2blog.controller;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.arpit.java2blog.exception.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

 private static final Logger logger = Logger
   .getLogger(HelloWorldController.class);

 @RequestMapping("/helloworld/{helloType}")
 public ModelAndView hello(@PathVariable("helloType") String helloType)
   throws CustomException, IOException {

  String helloWorldMessage="";
  if (helloType.equalsIgnoreCase("CustomException")) {
   throw new CustomException("Custom exception occured");
  } else if (helloType.equalsIgnoreCase("IOException")) {
   throw new IOException(" IO exception occured");
  } else {
   helloWorldMessage = "Hello world from java2blog!";
   
  }

  return new ModelAndView("hello", "message", helloWorldMessage);
 }

 @ExceptionHandler(CustomException.class)
 public ModelAndView catchCustomException(CustomException ex) {

  ModelAndView model = new ModelAndView("Custom_Exception");
  model.addObject("errorMessage", ex.getMessage());
  return model;
 }
 
 @ExceptionHandler(IOException.class)
 public ModelAndView catchIOException(IOException ex) {

  ModelAndView model = new ModelAndView("IOException");
  model.addObject("errorMessage", ex.getMessage());
  return model;
 }
}

Create ControllerAdvice named GlobalExceptionController.java

package org.arpit.java2blog.controller;

import java.io.IOException;

import org.arpit.java2blog.exception.CustomException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionController {

 @ExceptionHandler(CustomException.class)
 public ModelAndView catchCustomException(CustomException ex) {

  ModelAndView model = new ModelAndView("Custom_Exception");
  model.addObject("errorMessage", ex.getMessage());
  return model;
 }
 
 @ExceptionHandler(IOException.class)
 public ModelAndView catchCustomException(IOException ex) {

  ModelAndView model = new ModelAndView("IOException");
  model.addObject("errorMessage", ex.getMessage());
  return model;
 }
}

As you can see, we have annotated two method i.e. catchCustomException and catchIOException with @ExceptionHandler. These methods will handle CustomException and IOException respectively and these exceptions can be thrown by multiple controllers too.

Create view


Modify index.jsp as below
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HelloWorld</title>
</head>
<body>
Hello World!!
</body>
</html>

Create Custom_Excepion.jsp in /WEB-INF/ folder to handle CustomException exception.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Custom Exception</title>
</head>
<body>
${errorMessage}
</body>
</html>
Create IOException.jsp in /WEB-INF folder as below to handle IOException.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>IO Exception</title>
</head>
<body>
${errorMessage}
</body>
</html>

7) It 's time to do maven build.
Right click on project -> Run as -> Maven build
Maven build in eclipse

8) Provide goals as clean install (given below) and click on run
Maven build in eclipse

Run the application

9) Right click on project -> run as -> run on server
Select apache tomcat and click on finish
10) Lets hit below URL
http://localhost:8080/SpringMVCControllerAdviceExample/helloworld/hello


As you can see, it is working fine with above URL.
Now lets hit some URL which will throw exception and exception will be handled by @ExcpetionHandler in @ControllerAdvice class.

When you hit below URL.
http://localhost:8080/SpringMVCControllerAdviceExample/helloworld/CustomException


As you can see, when you hit above URL , CustomException is thrown and handled by catchCustomException method in @ControllerAdvice class.

When you hit below URL.
http://localhost:8080/SpringMVCControllerAdviceExample/helloworld/IOException




As you can see, when you hit above URL , CustomException is thrown and handled by catchIOException method in @ControllerAdvice class.

In this post , we will see how to do exceptional handling in Spring MVC using @ExceptionalHandler. You can use @ExceptionHandler to redirect to error view when exception occurs.
Lets understand this with the help of example:

Source code:

click to begin

20KB .zip


1) Create a dynamic web project using maven in eclipse named "SpringMVCExceptionalHandlerExample"

Maven dependencies 

2) Our pom.xml will look like below
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.arpit.java2blog</groupId>
  <artifactId>SpringRestfulWebServicesWithJSONExample</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringRestfulWebServicesWithJSONExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
  </dependency>

  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-core</artifactId>
   <version>${spring.version}</version>
  </dependency>
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>${spring.version}</version>
  </dependency>
   <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
             <version>2.4.1</version>
        </dependency>
 </dependencies>
 <build>
  <finalName>SpringRestfulWebServicesWithJSONExample</finalName>

  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>${jdk.version}</source>
     <target>${jdk.version}</target>
    </configuration>
   </plugin>
  </plugins>

 </build>
 <properties>
  <spring.version>4.2.1.RELEASE</spring.version>
  <jdk.version>1.7</jdk.version>
 </properties>
</project>

Spring application configuration:

3) Change web.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 version="3.0">
 <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>  
   <welcome-file>index.jsp</welcome-file>  
 
  </welcome-file-list>
 <servlet>
 <servlet-name>springrest</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>springrest</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>
4) create a xml file named springrest-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.

<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

 <mvc:annotation-driven/>
<context:component-scan base-package="org.arpit.java2blog.controller" />
 <bean
  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix">
   <value>/WEB-INF/</value>
  </property>
  <property name="suffix">
   <value>.jsp</value>
  </property>
 </bean>
 <mvc:default-servlet-handler/>
</beans>

Create Controller 

6) Create a controller named "HelloWorldController.java" in package org.arpit.java2blog.controller
package org.arpit.java2blog.controller;

import java.io.IOException;

import org.apache.log4j.Logger;
import org.arpit.java2blog.exception.CustomException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloWorldController {

	private static final Logger logger = Logger
			.getLogger(HelloWorldController.class);

	@RequestMapping("/helloworld/{helloType}")
	public ModelAndView hello(@PathVariable("helloType") String helloType)
			throws CustomException, IOException {

		String helloWorldMessage="";
		if (helloType.equalsIgnoreCase("CustomException")) {
			throw new CustomException("Custom exception occured");
		} else if (helloType.equalsIgnoreCase("IOException")) {
			throw new IOException(" IO exception occured");
		} else {
			helloWorldMessage = "Hello world from java2blog!";
			
		}

		return new ModelAndView("hello", "message", helloWorldMessage);
	}

	@ExceptionHandler(CustomException.class)
	public ModelAndView catchCustomException(CustomException ex) {

		ModelAndView model = new ModelAndView("Custom_Exception");
		model.addObject("errorMessage", ex.getMessage());
		return model;
	}
	
	@ExceptionHandler(IOException.class)
	public ModelAndView catchIOException(IOException ex) {

		ModelAndView model = new ModelAndView("IOException");
		model.addObject("errorMessage", ex.getMessage());
		return model;
	}
}

Create view

As you can see, we have annotated two method i.e. catchCustomException and catchIOException with @ExceptionHandler. These methods will handle CustomException and IOException respectively.
Modify index.jsp as below
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HelloWorld</title>
</head>
<body>
Hello World!!
</body>
</html>

Create Custom_Excepion.jsp in /WEB-INF/ folder to handle CustomException exception.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Custom Exception</title>
</head>
<body>
${errorMessage}
</body>
</html>
Create IOException.jsp in /WEB-INF folder as below to handle IOException.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>IO Exception</title>
</head>
<body>
${errorMessage}
</body>
</html>

7) It 's time to do maven build.
Right click on project -> Run as -> Maven build
Maven build in eclipse

8) Provide goals as clean install (given below) and click on run
Maven build in eclipse

Run the application

9) Right click on project -> run as -> run on server
Select apache tomcat and click on finish
10) Lets hit below URL
http://localhost:8080/SpringMVCExceptionalHandlerExample/helloworld/hello


As you can see, it is working fine with above URL.
Now lets hit some URL which will throw exception and exception will be handled by @ExcpetionHandler.

When you hit below URL.
http://localhost:8080/SpringMVCExceptionalHandlerExample/helloworld/CustomException


As you can see, when you hit above URL , CustomException is thrown and handled by catchCustomException method.

When you hit below URL.
http://localhost:8080/SpringMVCExceptionalHandlerExample/helloworld/IOException




As you can see, when you hit above URL , CustomException is thrown and handled by catchIOException method.

In this post, we are going to see integration of Spring MVC, hibernate and mysql CRUD example.
We have already seen integration of Spring Rest with hibernate in previous tutorial.

Spring MVC tutorial:

    Spring MVC hello world example Spring MVC Hibernate MySQL example Spring MVC interceptor example Spring MVC angularjs example Spring MVC @RequestMapping example Spring Component,Service, Repository and Controller example Spring MVC @ModelAttribute annotation example Spring MVC @RestController annotation example Spring MultiActionController Example Spring MVC ModelMap Spring MVC file upload example Spring restful web service example Spring restful web service json example Spring Restful web services CRUD example Spring security hello world example Spring security custom login form example
Here are steps to create a project with Spring MVC , hibernate and mySQL crud example.

Source code:

click to begin

20KB .zip


1) Create a dynamic web project using maven in eclipse named "SpringMVCHibernateCRUDExample"

Maven dependencies 

2) We are using Spring 4 and Hibernate 4 for this application. It should work with hibernate 3 also but we need to do small changes in hibernate configuration.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.arpit.java2blog</groupId>
	<artifactId>SpringMVCHibernateCRUDExample</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>SpringMVCHibernateCRUDExample Maven Webapp</name>
	<url>http://maven.apache.org</url>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.4.1</version>
		</dependency>
		<!-- Hibernate -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-core</artifactId>
			<version>${hibernate.version}</version>
		</dependency>
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-entitymanager</artifactId>
			<version>${hibernate.version}</version>
		</dependency>

		<!-- Apache Commons DBCP -->
		<dependency>
			<groupId>commons-dbcp</groupId>
			<artifactId>commons-dbcp</artifactId>
			<version>1.4</version>
		</dependency>
		<!-- Spring ORM -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- AspectJ -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjrt</artifactId>
			<version>${org.aspectj-version}</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.6</version>
		</dependency>
		<!-- https://mvnrepository.com/artifact/jstl/jstl -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
	</dependencies>
	<build>
		<finalName>SpringMVCHibernateCRUDExample</finalName>

		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>${jdk.version}</source>
					<target>${jdk.version}</target>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<failOnMissingWebXml>false</failOnMissingWebXml>
				</configuration>
			</plugin>
		</plugins>

	</build>
	<properties>
		<spring.version>4.2.1.RELEASE</spring.version>
		<security.version>4.0.3.RELEASE</security.version>
		<jdk.version>1.7</jdk.version>
		<hibernate.version>4.3.5.Final</hibernate.version>
		<org.aspectj-version>1.7.4</org.aspectj-version>
	</properties>
</project>

Spring application configuration:

3) Change web.xml as below:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	version="3.0">
	<display-name>Archetype Created Web Application</display-name>
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>/WEB-INF/applicationcontext.xml</param-value>
	</context-param>
	<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
	<servlet>
 <servlet-name>spring</servlet-name>
 <servlet-class>
  org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
 <servlet-name>spring</servlet-name>
 <url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>
4) create a xml file named spring-servlet.xml in /WEB-INF/ folder.
Please change context:component-scan if you want to use different package for spring to search for controller.Please refer to spring mvc hello world example for more understanding.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

	<annotation-driven />

	<resources mapping="/resources/**" location="/resources/" />

	<beans:bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<beans:property name="prefix" value="/WEB-INF/views/" />
		<beans:property name="suffix" value=".jsp" />
	</beans:bean>

	<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<beans:property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<beans:property name="url"
			value="jdbc:mysql://localhost:3306/CountryData" />
		<beans:property name="username" value="root" />
		<beans:property name="password" value="" />
	</beans:bean>

	<!-- Hibernate 4 SessionFactory Bean definition -->
	<beans:bean id="hibernate4AnnotatedSessionFactory"
		class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
		<beans:property name="dataSource" ref="dataSource" />
		<beans:property name="annotatedClasses">
			<beans:list>
				<beans:value>org.arpit.java2blog.model.Country</beans:value>
			</beans:list>
		</beans:property>
		<beans:property name="hibernateProperties">
			<beans:props>
				<beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
				</beans:prop>
				<beans:prop key="hibernate.show_sql">true</beans:prop>
			</beans:props>
		</beans:property>
	</beans:bean>

	<context:component-scan base-package="org.arpit.java2blog" />

	<tx:annotation-driven transaction-manager="transactionManager" />

	<beans:bean id="transactionManager"
		class="org.springframework.orm.hibernate4.HibernateTransactionManager">
		<beans:property name="sessionFactory"
			ref="hibernate4AnnotatedSessionFactory" />
	</beans:bean>


</beans:beans>

In Spring-servlet.xml, we have done hibernate configuration.
dataSource bean is used to specify java data source. We need to provide driver, URL , Username and Password.
transactionManager bean is used to configure hibernate transaction manager. hibernate4AnnotatedSessionFactory bean is used to configure FactoryBean that creates a Hibernate SessionFactory. This is the common way to set up a shared Hibernate SessionFactory in a Spring application context, so you can use this SessionFactory to inject in Hibernate data access objects.
Create a applicationcontext.xml in WEB-INF folder, this file is used for bean configuration as we are using spring-servlet.xml for bean configuration , we will keep this file empty.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
</beans:beans>

Create bean class 

4) Create a bean name "Country.java" in org.arpit.java2blog.bean.
package org.arpit.java2blog.model;

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

/*
 * This is our model class and it corresponds to Country table in database
 */
@Entity
@Table(name="COUNTRY")
public class Country{
 
 @Id
 @Column(name="id")
 @GeneratedValue(strategy=GenerationType.IDENTITY)
 int id;
 
 @Column(name="countryName")
 String countryName; 
 
 @Column(name="population")
 long population;
 
 public Country() {
  super();
 }
 public Country(int i, String countryName,long population) {
  super();
  this.id = i;
  this.countryName = countryName;
  this.population=population;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getCountryName() {
  return countryName;
 }
 public void setCountryName(String countryName) {
  this.countryName = countryName;
 }
 public long getPopulation() {
  return population;
 }
 public void setPopulation(long population) {
  this.population = population;
 } 
 
}
@Entity is used for making a persistent pojo class.For this java class,you will have corresponding table in database. @Column is used to map annotated attribute to corresponding column in table. So Create Country table in mysql database with following code:
CREATE TABLE COUNTRY
(
   id int PRIMARY KEY NOT NULL AUTO_INCREMENT,
   countryName varchar(100) NOT NULL,
   population int NOT NULL
)
;

Create Controller 

5) Create a controller named "CountryController.java" in package org.arpit.java2blog.controller
package org.arpit.java2blog.controller;


import java.util.List;

import org.arpit.java2blog.model.Country;
import org.arpit.java2blog.service.CountryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class CountryController {
	
	@Autowired
	CountryService countryService;
	
	@RequestMapping(value = "/getAllCountries", method = RequestMethod.GET, headers = "Accept=application/json")
	public String getCountries(Model model) {
		
		List<Country> listOfCountries = countryService.getAllCountries();
		model.addAttribute("country", new Country());
		model.addAttribute("listOfCountries", listOfCountries);
		return "countryDetails";
	}

	@RequestMapping(value = "/getCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
	public Country getCountryById(@PathVariable int id) {
		return countryService.getCountry(id);
	}

	@RequestMapping(value = "/addCountry", method = RequestMethod.POST, headers = "Accept=application/json")
	public String addCountry(@ModelAttribute("country") Country country) {	
		if(country.getId()==0)
		{
			countryService.addCountry(country);
		}
		else
		{	
			countryService.updateCountry(country);
		}
		
		return "redirect:/getAllCountries";
	}

	@RequestMapping(value = "/updateCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
	public String updateCountry(@PathVariable("id") int id,Model model) {
		 model.addAttribute("country", this.countryService.getCountry(id));
	        model.addAttribute("listOfCountries", this.countryService.getAllCountries());
	        return "countryDetails";
	}

	@RequestMapping(value = "/deleteCountry/{id}", method = RequestMethod.GET, headers = "Accept=application/json")
	public String deleteCountry(@PathVariable("id") int id) {
		countryService.deleteCountry(id);
		 return "redirect:/getAllCountries";

	}	
}

Create DAO class

Create a class CountryDAO.java in package org.arpit.java2blog.dao.  This class will execute hibernate statements while interacting with database.
package org.arpit.java2blog.dao;

import java.util.List;

import org.arpit.java2blog.model.Country;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class CountryDAO {

 @Autowired
 private SessionFactory sessionFactory;

 public void setSessionFactory(SessionFactory sf) {
  this.sessionFactory = sf;
 }

 public List<Country> getAllCountries() {
  Session session = this.sessionFactory.getCurrentSession();
  List<Country> countryList = session.createQuery("from Country").list();
  return countryList;
 }

 public Country getCountry(int id) {
  Session session = this.sessionFactory.getCurrentSession();
  Country country = (Country) session.load(Country.class, new Integer(id));
  return country;
 }

 public Country addCountry(Country country) {
  Session session = this.sessionFactory.getCurrentSession();
  session.persist(country);
  return country;
 }

 public void updateCountry(Country country) {
  Session session = this.sessionFactory.getCurrentSession();
  session.update(country);
 }

 public void deleteCountry(int id) {
  Session session = this.sessionFactory.getCurrentSession();
  Country p = (Country) session.load(Country.class, new Integer(id));
  if (null != p) {
   session.delete(p);
  }
 } 
}

@Repository is specialised component annotation which is used to create bean at DAO layer. We have use Autowired annotation to inject hibernate SessionFactory into CountryDAO class. We have already configured hibernate SessionFactory object in Spring-Servlet.xml file.

Create Service class

6) Create a class CountryService.java in package org.arpit.java2blog.service
It is service level class. It will call DAO layer class.
package org.arpit.java2blog.service;

import java.util.List;
import org.arpit.java2blog.dao.CountryDAO;
import org.arpit.java2blog.model.Country;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service("countryService")
public class CountryService {

 @Autowired
 CountryDAO countryDao;
 
 @Transactional
 public List<Country> getAllCountries() {
  return countryDao.getAllCountries();
 }

 @Transactional
 public Country getCountry(int id) {
  return countryDao.getCountry(id);
 }

 @Transactional
 public void addCountry(Country country) {
  countryDao.addCountry(country);
 }

 @Transactional
 public void updateCountry(Country country) {
  countryDao.updateCountry(country);

 }

 @Transactional
 public void deleteCountry(int id) {
  countryDao.deleteCountry(id);
 }
}

@Service is specialised component annotation which is used to create bean at Service layer.

Create view

Create view called countryDetails.jsp in WEB-INF/view/ folder.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<html>
<head>
<style>           
.blue-button{
	background: #25A6E1;
	filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#25A6E1',endColorstr='#188BC0',GradientType=0);
	padding:3px 5px;
	color:#fff;
	font-family:'Helvetica Neue',sans-serif;
	font-size:12px;
	border-radius:2px;
	-moz-border-radius:2px;
	-webkit-border-radius:4px;
	border:1px solid #1A87B9
}     
table {
  font-family: "Helvetica Neue", Helvetica, sans-serif;
   width: 50%;
}
th {
  background: SteelBlue;
  color: white;
}
 td,th{
                border: 1px solid gray;
                width: 25%;
                text-align: left;
                padding: 5px 10px;
            }
</style>
</head>
<body>
<form:form method="post" modelAttribute="country" action="/SpringMVCHibernateCRUDExample/addCountry">
<table>
		<tr>
			<th colspan="2">Add Country</th>
		</tr>
		<tr>
	<form:hidden path="id" />
          <td><form:label path="countryName">Country Name:</form:label></td>
          <td><form:input path="countryName" size="30" maxlength="30"></form:input></td>
        </tr>
		<tr>
			    <td><form:label path="population">Population:</form:label></td>
          <td><form:input path="population" size="30" maxlength="30"></form:input></td>
		</tr>
		<tr>
			<td colspan="2"><input type="submit"
				class="blue-button" /></td>
		</tr>
	</table> 
</form:form>
</br>
<h3>Country List</h3>
<c:if test="${!empty listOfCountries}">
	<table class="tg">
	<tr>
		<th width="80">Id</th>
		<th width="120">Country Name</th>
		<th width="120">Population</th>
		<th width="60">Edit</th>
		<th width="60">Delete</th>
	</tr>
	<c:forEach items="${listOfCountries}" var="country">
		<tr>
			<td>${country.id}</td>
			<td>${country.countryName}</td>
			<td>${country.population}</td>
			<td><a href="<c:url value='/updateCountry/${country.id}' />" >Edit</a></td>
			<td><a href="<c:url value='/deleteCountry/${country.id}' />" >Delete</a></td>
		</tr>
	</c:forEach>
	</table>
</c:if>
</body>
</html>

8) It 's time to do maven build.
Right click on project -> Run as -> Maven build
Maven build in eclipse

9) Provide goals as clean install (given below) and click on run
Maven build in eclipse

Run the application

10) Right click on project -> run as -> run on server
Select apache tomcat and click on finish

11)  Now lets hit below URL to getAllCountries.
http://localhost:8080/SpringMVCHibernateCRUDExample/getAllCountries
You will get below screen:
Empty Country List Spring MVC hibernate
As you can see, we did not add any country to the list, so it is empty.
Lets add Country named India to country list and click submit.
Similarly we will add China , Bhutan and Nepal respectively and you will see below screen.
All Country List Spring MVC hibernate


Lets edit population of Bhutan to 15000. Click on edit button corresponds to Bhutan.

When you click on submit, you will get below screen.
Lets delete country China from above list, click on delete button corresponds to 2nd row.
You will see below screen.
As you can see, china got deleted from above list.

Project structure:

Spring MVC Hibernate CRUD example

We are done with Spring MVC hibernate MySQL CRUD example. If you are still facing any issue, please comment.

If you getting 404 error with above steps, you may need to follow below steps:


1) If you are getting this warning into your Tomcat startup console log, then it can cause the issue

WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.j2ee.server: JAXRSJsonCRUDExample' did not find a matching property.

This particular warning basically means that the <Context> element in Tomcat's server.xml contains an unknown attribute source and that Tomcat doesn't know what to do with this attribute and therefore will ignore it.
To resolve this in eclipse,
Remove the project from the server from the Server View. Right click on server -> add and remove

then remove project from server configuration.
Then run the project under the same server. Warning should be removed now
Or if warning still remains then
  • Go to server view
  • Double click on your tomcat server. It will open the server configuration.
  • Under server options check ‘Publish module contents to separate XML files’ checkbox. 
  • Restart your server. This time your page will come without any issues.
2) Try to update Maven project.
Right click on project ->Maven-> update project
Update Maven project
then

This should solve you issues.

Enti

 

Java tutorial for beginners Copyright © 2012