Java

Java is a set of computer software and specifications developed by Sun Microsystems, which was later acquired by the Oracle Corporation, that provides a system for developing application software and deploying it in a cross-platform computing environment. Java is used in a wide variety of computing platforms from embedded devices and mobile phones to enterprise servers and supercomputers.

Spring Logo

Spring Framework

The Spring Framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications - on any kind of deployment platform. A key element of Spring is infrastructural support at the application level: Spring focuses on the "plumbing" of enterprise applications so that teams can focus on application-level business logic, without unnecessary ties to specific deployment environments.

Hibernate Logo

Hibernate Framework

Hibernate ORM is an object-relational mapping framework for the Java language. It provides a framework for mapping an object-oriented domain model to a relational database.

Monday, September 28, 2015

forEach() method in Iterable interface and Stream interface in Java 8

To iterate a collection, we have several ways:

  • Using Normal for loop
  • Using Enhanced for loop
  • Using Iterator (java.util.Iterator)
1. Using Normal for loop:
List<String> names = new ArrayList<>();
names.add("Ranga");
names.add("Reddy");
names.add("Raja");
names.add("Vasu");
        
System.out.println("Using normal for loop..");
for(int index = 0; index < names.size(); index++) {
    System.out.println(names.get(index));
}
2. Using Enhanced for loop:
System.out.println("\nUsing enhanced for loop..");
for(String name: names) {
    System.out.println(name);
}
3. Using Iterator (java.util.Iterator):
System.out.println("\nUsing Iteraotr..");
Iterator<String> namesIterator = names.iterator();
while(namesIterator.hasNext()) {
    System.out.println(namesIterator.next());
}

In java 8, a new method is introduced to iterate collection ie. forEach(). This forEach() is defined in two places namely, inside java.lang.Iterable interface and java.util.stream.Stream interface.
4. Using Iterable (java.lang.Iterable):
Collection classes that implements Iterable interface (List, Set) have a default method called a forEach(), it takes one argument i.e Consumer functional interface.
package java.lang;

public interface Iterable<T> {
    --------
    default void forEach(Consumer<? super T> action) {
        Objects.requireNonNull(action);
        for (T t : this) {
            action.accept(t);
        }
    }
   --------
}
System.out.println("\nUsing Consumer..");
Consumer<String> namesConsumer = (name) -> System.out.println(name);                 
names.forEach(namesConsumer);
5. Using Streams (java.util.Stream):
Same as Iterable interface forEach() stream interface also having one forEach() method it will take Consumer functional interface. Through streams, we can iterate collection (List, Set, Map) values serial and parallel.
package java.util.stream;
public interface Stream<T> extends BaseStream<T, Stream<T>> {
    --------
    void forEach(Consumer<? super T> action);
    --------
}
System.out.println("\nUsing Stream forEach..");                  
names.stream().forEach((name) -> System.out.println(name));
        
System.out.println("\nUsing Parallel Stream forEach..");                     
names.parallelStream().forEach((name) -> System.out.println(name));
If you we use parallelStream().forEach() method, there is no guarantee to which order elements will display. To make same order we need to use forEachOrdered() method.

Note: Instead of using Iterable forEach() method prefer to use Streams().forEach() because streams are lazy and not evaluated until a terminal operation is called.
package com.ranga.foreach;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author Ranga Reddy
 * @version 1.0
 */
public class ForEachDemo {
    public static void main(String[] args) {
                
        List<String> names = new ArrayList<>();
        names.add("Ranga");
        names.add("Reddy");
        names.add("Raja");
        names.add("Vasu");
        
        System.out.println("\nPrinting the list values using forEach()..");              
        names.stream().forEach((name) -> System.out.println(name));
        
        
        System.out.println("\nPrinting the set values using forEach()..");
        Set<String> setNames = new HashSet<>(names);
        setNames.add("Ranga");
        setNames.forEach(System.out::println);
        
        Map<String, String> namesMap = new HashMap<>();
        namesMap.put("name1", "Ranga");
        namesMap.put("name2", "Reddy");
        namesMap.put("name3", "Vasu");
        namesMap.put("name4", "Raja");
        
        System.out.println("\nPrinting the hashmap values using forEach()..");
        namesMap.forEach((key, value) -> System.out.println("Key: "+key +", Value: "+value));
    }
}
Output:
Printing the list values using forEach()..
Ranga
Reddy
Raja
Vasu

Printing the set values using forEach()..
Raja
Reddy
Vasu
Ranga

Printing the hashmap values using forEach()..
Key: name4, Value: Raja
Key: name3, Value: Vasu
Key: name2, Value: Reddy
Key: name1, Value: Ranga

Sunday, September 27, 2015

Lambda Expressions in Java 8

Lambda Expressions:
  • Lambda expression is an anonymous function without any declarations. 
  • Lambda Expression are useful to write shorthand code and hence saves the effort of writing lengthy code. 
  • It promotes developer productivity, better readable and reliable code.
  • Lambda expressions can be converted to functional interfaces.
  • Lambda expressions can access effectively final variables from the enclosing scope..
Syntax of Lambda expression:
(arguments) -> {body}

Example of Lambda expression:
public class LambdaExpressions
{
  public static void main(String[] args)
  {        
    // Old way
    Runnable runnable = new Runnable() {
        public void run() {
            System.out.println("With out using Lambda Expressions .... ");
        }
    };
    
    Thread thread = new Thread(runnable);    
    thread.start();
    
    // Using Lambda Expressions
    Runnable runnable2 = () -> { System.out.println("With using Lambda Expressions .... ");};
    
    Thread thread2 = new Thread(runnable2);    
    thread2.start();    
  }
}
Output:
With out using Lambda Expressions .... 
With using Lambda Expressions .... 
Lambda expression arguments can contain zero or more arguments.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");

new Thread(() -> { System.out.println("Empty arguments.");}) {      // empty arguments          
}.run();;
        
names.forEach(name -> System.out.println(name));            // one argument with out specifying data type 
names.forEach((name) -> System.out.println(name));          // one argument with out specifying data type
names.forEach((String name) -> System.out.println(name));   // one argument with specifying data type
Note: We can omit the datatype of the parameters in a lambda expression. And also we can omit the parentheses if there is only one parameter.

Lambda expression body can contain any number of statements or with out statement also.
If body contains more than one statement then curly braces is mandatory otherwise it is optional.
List<String> names = new ArrayList<String>();
names.add("Ranga");
names.add("Reddy");
names.add("Vasu");
names.add("Raja");
names.add("Viond");
names.add("Manoj");
        
names.forEach(((name) -> System.out.println(name))); // with out braces
        
names.forEach((name) -> {                            // with braces 
    System.out.println(name);
    System.out.println("Hello Mr. "+name);          
});

Sunday, September 20, 2015

Functional Interfaces (java.util.function) in Java 8



Functional Interfaces (java.util.function):

  • Functional interface is also called as Single Abstract Method interfaces.
  • A functional interface is an interface with a single abstract method
  • Note: A functional interface can redeclare the methods in the Object class.
  • The Java API has many one-method interfaces such as java.lang.Runnable, java.util.concurrent.Callable, java.util.Comparator, java.awt.event.ActionListener etc.
      • public interface Runnable { void run(); } 
      • public interface Callable<V> { V call() throws Exception; }
      • public interface ActionListener { void actionPerformed(ActionEvent e); } 
      • public interface Comparator<T> { int compare(T obj1, T obj2); boolean equals(Object obj); } 
  • Instances of functional interfaces can be created with lambda expressions, method references, or constructor references. For example,
                // Before Java8
Runnable runnable1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("runnable1");
}
});
runnable1.run();
// Java8
Runnable runnable2 = () -> System.out.println("runnable2");
runnable2.run();   
  • In java 8, to declare functional interfaces there is a new annotation is introduced called @FunctionalInterface. By using this annotation we will ensure that the functional interface will not have more than one abstract method. If we try to add one more abstract method it will raises the compile timer error. 
                Example 1: 
                @FunctionalInterface 
                interface Greeting {
              public void greeting(String message);
                }
                The above Greeting functional interface is valid interface because it contains only one abstract method. 

                Example 2: 
                @FunctionalInterface 
                interface Animal {
               public void speak();
               public default void name() {
            System.out.println("Hay I am animal");
               }
                }
                The above Animal functional interface is valid because in functional interface we can keep n number of default methods.

               Example 3:
                @FunctionalInterface 

                interface Test {
              public void doWork();
              public boolean equals(Object obj);
              public String toString();
                }
                The above Test functional interface is valid because in function interface we can declare the abstract methods from the java.lang.Object class.
               
                Example 4:
                @FunctionalInterface 

                interface EmptyInterface {
                      
                }
                The above EmptyInterface functional interface is not valid because it does not contain any abstract method.

                Example 5:
                @FunctionalInterface 

                interface MultipleMethodsInterface {
              public void doWork();
              public boolean equals();
                }
                The above MultipleMethodsInterface functional interface is not valid because it contains more than one abstract method.

                Example 6:
                @FunctionalInterface 

                interface Greeting {
              public void sayGreeting();
              public boolean equals();
                }


                interface AnotherGreeting extends Greeting {
              public boolean equals();
                }

                The above AnotherGreeting functional interface is valid because it is inheriting sayGreeting() method and this sayGreeting() method is abstract.

                Example 7:
                @FunctionalInterface 

                interface Greeting2 {
              public void sayGreeting();
              public boolean equals();
                }


                interface AnotherGreeting2 extends Greeting2 {
              public void sayAnotherGreeting();
              public boolean equals();
                }

                The above AnotherGreeting2 functional interface is not valid because it is inheriting sayGreeting() abstract method and also it contains one more abstract method say sayAnotherGreeting() method.
  • The major benefit of functional interface is that we can use lambda expressions to instantiate them and avoid using bulky anonymous class implementation.
  • The advantage of functional interface over normal interface is we can define method definition inside Interface using default modifier which helps to modify existing Interface with out breakage of application.
  • Java 8 Collections API has rewritten and new Stream API is provided that uses a lot of functional interfaces. Java 8 has defined a lot of functional interfaces in java.util.function package, some of the useful ones are Consumer, Supplier, Function and Predicate etc. You can find more here. How to use above functional interface we can see in Stream API examples.
Happy Learning..!

Saturday, September 19, 2015

Difference between ServletConfig and ServletContext

In this post, we are going to see the difference between ServletConfig and ServletContext.

Difference between ServletConfig and ServletContext:

ServletConfigServletContext(It should have been ApplicationContext)
One ServletConfig object is created per servlet One ServletContext object is created per Application
Can be used to pass deployment time information to the Servlet. Information is stored as parameters in the deployment descriptor(web.xml) Can be used to share Application level information across servlets and is this information is also stored in the web.xml as well as parameters (So it kind of acts as GlobalContext or Application Context)
Provides a set of methods to set and get the initialization configuration information Provides a set of methods to the servlet so that servlet can communicate with the Container
------------------------Servlet can access a ServletContext object only through ServletConfig object

Working with ServletConfig:

web.xml: 
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.ranga.LoginServlet</servlet-class>
<init-param>
<param-name>username</param-name>
<param-value>ranga</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>ranga</param-value>
</init-param>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
LoginServlet.java    
package com.ranga;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Ranga Reddy
* @version 1.0
*/

public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = -2226127949360374211L;
protected String username = null, password = null;

public void init(ServletConfig servletConfig) throws ServletException {
this.username = servletConfig.getInitParameter("username");
this.password = servletConfig.getInitParameter("password");
}

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("<html><body> Username:" + this.username + ", Password: "+this.password+" </body></html>");
}
}
Getting init parameters inside the servlet
servletConfig.getInitParameter("username");

Working with ServletContext:

web.xml:
 <context-param>
<param-name>username</param-name>
<param-value>ranga</param-value>
</context-param>

<context-param>
<param-name>password</param-name>
<param-value>ranga</param-value>
</context-param>

<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.ranga.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
LoginServlet.java
package com.ranga;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* @author Ranga Reddy
* @version 1.0
*/

public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = -2226127949360374211L;
protected String username = null, password = null;

public void init(ServletConfig servletConfig) throws ServletException {

ServletContext servletContext = servletConfig.getServletContext();
this.username = servletContext.getInitParameter("username");
this.password = servletContext.getInitParameter("password");
}

public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.getWriter().write("<html><body> Username:" + this.username + ", Password: "+this.password+" </body></html>");
}
}
Accessing context params in Servlet
servletConfig.getServletContext().getInitParameter("username");
Accessing context params in JSP
<% getServletContext().getInitParameter("username"); %>

Remove duplicate record in table

In this post, we are going to see how to remove duplicate records from table.

Create a test table
mysql> CREATE TABLE test_table (`id` int(11) DEFAULT NULL,`name` varchar(10) DEFAULT NULL);
Insert duplicate values in test table.
mysql> insert into test_table values (1,'aaa'),(1,'aaa'),(1,'aaa'),(1,'bbb'),(1,'bbb'),(1,'bbb');
mysql> select * from test_table;
+------+------+
| id | name |
+------+------+
| 1 | aaa |
| 1 | aaa |
| 1 | aaa |
| 1 | bbb |
| 1 | bbb |
| 1 | bbb |
+------+------+
Remove duplicate rows from test table
mysql> alter IGNORE table test_table add UNIQUE key (id,name);
Records: 6 Duplicates: 4 Warnings: 0
mysql> select * from test_table ;
+------+------+
| id | name |
+------+------+
| 1 | aaa |
| 1 | bbb |
+------+------+

Friday, September 11, 2015

Write a Java program to get unique characters from String

In this post, we are going to see how to get unique characters from string.
There are several ways to get unique characters from string. In this post, i have implemented two ways.
1. using boolean array.
2. using map.
1. Using Boolean array: In this technique, first we need to convert string into char array. After that we need to iterate all characters. While iterating we need to check that character is already added to array or not. If it is not added then we need to add that character to boolean array and append that character to stringbuilder. If it is already added that character to boolean array, skipping that character to add boolean array.
Code: 
public static String getUniqueCharsUsingBooleanArray(String input) {
        if (input == null || input.length() == 0)
            return input;

        boolean uniqueChars[] = new boolean[256];
        StringBuilder sb = new StringBuilder();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (!uniqueChars[ch]) {
                uniqueChars[ch] = true;
                sb.append(ch);
            }
        }
        return sb.toString();
}
2. Using Map: In this technique, first we need to convert string into char array. After that we need to iterate each character. While iterating we need to check that character is already added or not. If it is not added, adding that character to map and making count is 1. If it is already added then increment that character with count +1. Once all iteration is done then we need to iterate map and append to that character to stringbuilder. Finally convert this stringbuilder to string using toString() method.
Code:
public static String getUniqueCharsUsingMap(String input) {
        if (input == null || input.length() == 0)
            return input;

        Map<Character, Integer> map = new LinkedHashMap<>();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (map.get(ch) == null) {
                map.put(ch, 1);
            } else {
                map.put(ch, map.get(ch) + 1);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Character uniqueChar : map.keySet()) {
            sb.append(uniqueChar);
        }
        return sb.toString();
}

Program:
package com.ranga;

import java.util.LinkedHashMap;
import java.util.Map;

public class UniqueCharecters {

    public static void main(String[] args) {
        String input = "my name is ranga reddy";
        System.out.println("Unique Characters using way1: " + getUniqueCharsUsingMap(input));
        System.out.println("Unique Characters using way2: " + getUniqueCharsUsingBooleanArray(input));
    }

    public static String getUniqueCharsUsingBooleanArray(String input) {
        if (input == null || input.length() == 0)
            return input;

        boolean uniqueChars[] = new boolean[256];
        StringBuilder sb = new StringBuilder();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (!uniqueChars[ch]) {
                uniqueChars[ch] = true;
                sb.append(ch);
            }
        }
        return sb.toString();
    }

    public static String getUniqueCharsUsingMap(String input) {
        if (input == null || input.length() == 0)
            return input;

        Map<Character, Integer> map = new LinkedHashMap<>();
        char chars[] = input.toCharArray();
        for (char ch : chars) {
            if (map.get(ch) == null) {
                map.put(ch, 1);
            } else {
                map.put(ch, map.get(ch) + 1);
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Character uniqueChar : map.keySet()) {
            sb.append(uniqueChar);
        }
        return sb.toString();
    }
}
Output:
Unique Characters using way1: my naeisrgd
Unique Characters using way2: my naeisrgd
Happy Learning ....!

Saturday, September 5, 2015

Spring 4 MVC + Hibernate 4 + MySQL 5 + Maven 3 integration : CRUD operations example

In this post, we are going to learn how to integrate Spring4 MVC with Hibernate4 application with Maven build tool and will perform CRUD operations using MySql Database.
Project Structure:
The following screenshot shows final structure of the project:

Tools and Technologies:

  • Spring 4.1.5 RELEASE
  • Hibernate 4.3.8 Final
  • MySQL 5.1.10
  • Java 8
  • Eclipse
  • Tomcat 8
  • Maven 3

Step 1: Create Database Table
For this demo, i have created a Employees table in MySQL database. Find the script to create the Employees table.
create database ranga;
create table Employees (
id bigint not null auto_increment,
age integer,
name varchar(255),
salary float,
primary key (id)
)
Step 2: Updating the Maven Dependencies
Update pom.xml to include required dependencies
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/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.ranga</groupId>
<artifactId>Spring4Hiberante4Integration</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>Spring4Hiberante4Integration</name>

<!-- Specifying the Versions of Spring, Hiberante, MySQL etc -->
<properties>
<spring.version>4.1.5.RELEASE</spring.version>
<hibernate.version>4.3.8.Final</hibernate.version>
<mysql.version>5.1.10</mysql.version>
<junit-version>4.11</junit-version>
<servlet-api-version>3.1.0</servlet-api-version>
<jsp-version>2.1</jsp-version>
<jstl-version>1.2</jstl-version>
<java.version>1.8</java.version>
</properties>

<!-- Specifying the Dependencies -->
<dependencies>

<!-- Spring 4 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>

<!-- Hibernate 4 dependencies -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>

<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-c3p0</artifactId>
<version>${hibernate.version}</version>
</dependency>

<!--MYSQL Connector -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>

<!-- Servlet and JSP -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet-api-version}</version>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>${jsp-version}</version>
<scope>provided</scope>
</dependency>

<!-- JSTL dependency -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>${jstl-version}</version>
</dependency>

<!-- JUnit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit-version}</version>
<scope>test</scope>
</dependency>

</dependencies>

<build>
<finalName>Spring4Hiberante4Integration</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.3</version>
<executions>
<execution>
<phase>package</phase>
<configuration>
<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
</configuration>
</execution>
</executions>
</plugin>

<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<includes>
<include>**/*Tests.java</include>
</includes>
</configuration>
</plugin>
</plugins>
</build>

</project>
Step 3: Deployment Descriptor (web.xml)
We need to plugin spring framework in our web application, that is done by configuring Spring framework DispatcherServlet as front controller.

web.xml
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
>

<display-name>Spring4 MVC Hibernate4 Application</display-name>

<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Step 4: Spring Configuration file (mvc-dispatcher-servlet.xml)
mvc-dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"
>


<!-- Specifying base package of the Components like Controller, Service,
DAO -->

<context:component-scan
base-package="com.ranga" />


<!-- Getting Database properties -->
<context:property-placeholder location="classpath:application.properties" />

<mvc:annotation-driven />

<!-- Specifying the Resource location to load JS, CSS, Images etc -->
<mvc:resources mapping="/resources/**" location="/resources/" />

<!-- View Resolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">

<property name="prefix" value="/WEB-INF/pages/" />
<property name="suffix" value=".jsp" />
</bean>

<!-- DataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">

<property name="driverClass" value="${database.driverClass}" />
<property name="jdbcUrl" value="${database.url}" />
<property name="user" value="${database.username}" />
<property name="password" value="${database.password}" />

<property name="acquireIncrement" value="${connection.acquireIncrement}" />
<property name="minPoolSize" value="${connection.minPoolSize}" />
<property name="maxPoolSize" value="${connection.maxPoolSize}" />
<property name="maxIdleTime" value="${connection.maxIdleTime}" />
</bean>

<!-- Hibernate SessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

<property name="dataSource" ref="dataSource"></property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
<property name="packagesToScan" value="com.ranga.entity"></property>
</bean>

<!-- Transaction -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">

<property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager" />
</beans>
Step 5: Declaring the hibernate and database properties
application.properties
#Database related properties
database.driverClass=com.mysql.jdbc.Driver
database.url=jdbc:mysql:///ranga
database.username=ranga
database.password=ranga

#Hibernate related properties
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.hbm2ddl.auto=update
hibernate.show_sql=true
hibernate.format_sql=true

#Connection pool related properties
connection.acquireIncrement=2
connection.minPoolSize=20
connection.maxPoolSize=50
connection.maxIdleTime=600
Step 6:  Persistence Layer
Employee.java
package com.ranga.entity;

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

import java.io.Serializable;
/**
* @author Ranga Reddy
* @version 1.0
*
*/

@Entity
@Table(name = "Employees")
public class Employee implements Serializable {

private static final long serialVersionUID = -7988799579036225137L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;

@Column
private String name;

@Column
private int age;

@Column
private float salary;

public Employee() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}

@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
Step 7: Utility Class
HibernateUtil.java
package com.ranga.util;

import java.io.Serializable;
import java.util.List;

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

/**
* @author Ranga Reddy
* @version 1.0
*/

@Repository
public class HibernateUtil {

@Autowired
private SessionFactory sessionFactory;

public <T> Serializable create(final T entity) {
return sessionFactory.getCurrentSession().save(entity);
}

public <T> T update(final T entity) {
sessionFactory.getCurrentSession().update(entity);
return entity;
}

public <T> void delete(final T entity) {
sessionFactory.getCurrentSession().delete(entity);
}

public <T> void delete(Serializable id, Class<T> entityClass) {
T entity = fetchById(id, entityClass);
delete(entity);
}

@SuppressWarnings("unchecked")
public <T> List<T> fetchAll(Class<T> entityClass) {
return sessionFactory.getCurrentSession().createQuery(" FROM "+entityClass.getName()).list();
}

@SuppressWarnings("rawtypes")
public <T> List fetchAll(String query) {
return sessionFactory.getCurrentSession().createSQLQuery(query).list();
}

@SuppressWarnings("unchecked")
public <T> T fetchById(Serializable id, Class<T> entityClass) {
return (T)sessionFactory.getCurrentSession().get(entityClass, id);
}
}
Step 8: DAO Layer
EmployeeDAO.java
package com.ranga.dao;

import java.util.List;

import com.ranga.entity.Employee;

/**
* @author Ranga Reddy
* @version 1.0
*/

public interface EmployeeDAO {
public long createEmployee(Employee employee);
public Employee updateEmployee(Employee employee);
public void deleteEmployee(long id);
public List<Employee> getAllEmployees();
public Employee getEmployee(long id);
public List<Employee> getAllEmployees(String employeeName);
}
EmployeeDAOImpl.java
package com.ranga.dao.impl;

import com.ranga.dao.EmployeeDAO;
import com.ranga.entity.Employee;
import com.ranga.util.HibernateUtil;

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

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
* @author Ranga Reddy
* @version 1.0
*/


@Repository
public class EmployeeDAOImpl implements EmployeeDAO {

public EmployeeDAOImpl() {
System.out.println("EmployeeDAOImpl");
}

@Autowired
private HibernateUtil hibernateUtil;

@Override
public long createEmployee(Employee employee) {
return (Long) hibernateUtil.create(employee);
}

@Override
public Employee updateEmployee(Employee employee) {
return hibernateUtil.update(employee);
}

@Override
public void deleteEmployee(long id) {
Employee employee = new Employee();
employee.setId(id);
hibernateUtil.delete(employee);
}

@Override
public List<Employee> getAllEmployees() {
return hibernateUtil.fetchAll(Employee.class);
}

@Override
public Employee getEmployee(long id) {
return hibernateUtil.fetchById(id, Employee.class);
}

@SuppressWarnings("unchecked")
@Override
public List<Employee> getAllEmployees(String employeeName) {
String query = "SELECT e.* FROM Employees e WHERE e.name like '%"+ employeeName +"%'";
List<Object[]> employeeObjects = hibernateUtil.fetchAll(query);
List<Employee> employees = new ArrayList<Employee>();
for(Object[] employeeObject: employeeObjects) {
Employee employee = new Employee();
long id = ((BigInteger) employeeObject[0]).longValue();
int age = (int) employeeObject[1];
String name = (String) employeeObject[2];
float salary = (float) employeeObject[3];
employee.setId(id);
employee.setName(name);
employee.setAge(age);
employee.setSalary(salary);
employees.add(employee);
}
System.out.println(employees);
return employees;
}
}
Step 8: Service Layer ( Service & Service Impl)

EmployeeService.java
package com.ranga.service;
import com.ranga.entity.Employee;

import java.util.List;

/**
* @author Ranga Reddy
* @version 1.0
*/

public interface EmployeeService {
public long createEmployee(Employee employee);
public Employee updateEmployee(Employee employee);
public void deleteEmployee(long id);
public List<Employee> getAllEmployees();
public Employee getEmployee(long id);
public List<Employee> getAllEmployees(String employeeName);
}
EmployeeServiceImpl.java
package com.ranga.service.impl;
import com.ranga.dao.EmployeeDAO;
import com.ranga.entity.Employee;
import com.ranga.service.EmployeeService;

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

import java.util.List;
/**
* @author Ranga Reddy
* @version 1.0
*/

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

public EmployeeServiceImpl() {
System.out.println("EmployeeServiceImpl()");
}

@Autowired
private EmployeeDAO employeeDAO;

@Override
public long createEmployee(Employee employee) {
return employeeDAO.createEmployee(employee);
}
@Override
public Employee updateEmployee(Employee employee) {
return employeeDAO.updateEmployee(employee);
}
@Override
public void deleteEmployee(long id) {
employeeDAO.deleteEmployee(id);
}
@Override
public List<Employee> getAllEmployees() {
return employeeDAO.getAllEmployees();
}
@Override
public Employee getEmployee(long id) {
return employeeDAO.getEmployee(id);
}
@Override
public List<Employee> getAllEmployees(String employeeName) {
return employeeDAO.getAllEmployees(employeeName);
}
}
Step 9: Controller Layer
EmployeeController.java
package com.ranga.controller;
import com.ranga.entity.Employee;
import com.ranga.service.EmployeeService;

import org.jboss.logging.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

/**
* @author Ranga Reddy
* @version 1.0
*/

@Controller
public class EmployeeController {

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

public EmployeeController() {
System.out.println("EmployeeController()");
}

@Autowired
private EmployeeService employeeService;

@RequestMapping("createEmployee")
public ModelAndView createEmployee(@ModelAttribute Employee employee) {
logger.info("Creating Employee. Data: "+employee);
return new ModelAndView("employeeForm");
}

@RequestMapping("editEmployee")
public ModelAndView editEmployee(@RequestParam long id, @ModelAttribute Employee employee) {
logger.info("Updating the Employee for the Id "+id);
employee = employeeService.getEmployee(id);
return new ModelAndView("employeeForm", "employeeObject", employee);
}

@RequestMapping("saveEmployee")
public ModelAndView saveEmployee(@ModelAttribute Employee employee) {
logger.info("Saving the Employee. Data : "+employee);
if(employee.getId() == 0){ // if employee id is 0 then creating the employee other updating the employee
employeeService.createEmployee(employee);
} else {
employeeService.updateEmployee(employee);
}
return new ModelAndView("redirect:getAllEmployees");
}

@RequestMapping("deleteEmployee")
public ModelAndView deleteEmployee(@RequestParam long id) {
logger.info("Deleting the Employee. Id : "+id);
employeeService.deleteEmployee(id);
return new ModelAndView("redirect:getAllEmployees");
}

@RequestMapping(value = {"getAllEmployees", "/"})
public ModelAndView getAllEmployees() {
logger.info("Getting the all Employees.");
List<Employee> employeeList = employeeService.getAllEmployees();
return new ModelAndView("employeeList", "employeeList", employeeList);
}

@RequestMapping("searchEmployee")
public ModelAndView searchEmployee(@RequestParam("searchName") String searchName) {
logger.info("Searching the Employee. Employee Names: "+searchName);
List<Employee> employeeList = employeeService.getAllEmployees(searchName);
return new ModelAndView("employeeList", "employeeList", employeeList);
}
}
Step 9: View Layer
employeeList.jsp
<%--
User: Ranga Reddy
Date: 09/05/2015
Time: 6:52 PM
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!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>Employees List</title>
<!-- Bootstrap CSS -->
<%-- <link href="<c:url value="/resources/css/bootstrap.min.css" />" rel="stylesheet"> --%>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style type="text/css">
.myrow-container {
margin: 20px;
}
</style>
</head>
<body class=".container-fluid">
<div class="container myrow-container">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">
<div align="left"><b>Employees List</b> </div>
<div align="right"><a href="createEmployee">Add New Employee</a></div>
</h3>
</div>
<div class="panel-body">
<c:if test="${empty employeeList}">
There are no Employees
</c:if>
<c:if test="${not empty employeeList}">

<form action="searchEmployee">
<div class="row">
<div class="col-md-6"><div class="col-md-6">Search Employees:</div><div class="col-md-6"> <input type="text" name="searchName" id="searchName"> </div></div>
<div class="col-md-4"><input class="btn btn-success" type='submit' value='Search'/></div>
</div>
</form>

<table class="table table-hover table-bordered">
<thead style="background-color: #bce8f1;">
<tr>
<th>Id</th>
<th>Name</th>
<th>Age</th>
<th>Salary</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<c:forEach items="${employeeList}" var="emp">
<tr>
<th><c:out value="${emp.id}"/></th>
<th><c:out value="${emp.name}"/></th>
<th><c:out value="${emp.age}"/></th>
<th><c:out value="${emp.salary}"/></th>
<th><a href="editEmployee?id=<c:out value='${emp.id}'/>">Edit</a></th>
<th><a href="deleteEmployee?id=<c:out value='${emp.id}'/>">Delete</a></th>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<%-- <script src="<c:url value="/resources/js/jquery-2.1.3.js"/>"></script>
<script src="<c:url value="/resources/js/bootstrap.min.js"/>"></script>
--%>

</body>
</html>
employeeForm.jsp
<%--
User: Ranga Reddy
Date: 09/05/2015
Time: 6:52 PM
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="author" content="Ranga Reddy">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Employee Information</title>
<!-- Bootstrap CSS -->
<%-- <link href="<c:url value="/resources/css/bootstrap.min.css" />" rel="stylesheet"> --%>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<style type="text/css">
.myrow-container{
margin: 20px;
}
</style>
</head>
<body class=".container-fluid">
<div class="container myrow-container">
<div class="panel panel-success">
<div class="panel-heading">
<h3 class="panel-title">
Employee Details
</h3>
</div>
<div class="panel-body">
<form:form id="employeeRegisterForm" cssClass="form-horizontal" modelAttribute="employee" method="post" action="saveEmployee">

<div class="form-group">
<div class="control-label col-xs-3"> <form:label path="name" >Name</form:label> </div>
<div class="col-xs-6">
<form:hidden path="id" value="${employeeObject.id}"/>
<form:input cssClass="form-control" path="name" value="${employeeObject.name}"/>
</div>
</div>

<div class="form-group">
<form:label path="age" cssClass="control-label col-xs-3">Age</form:label>
<div class="col-xs-6">
<form:input cssClass="form-control" path="age" value="${employeeObject.age}"/>
</div>
</div>

<div class="form-group">
<div class="control-label col-xs-3"><form:label path="salary">Salary</form:label></div>
<div class="col-xs-6">
<form:input cssClass="form-control" path="salary" value="${employeeObject.salary}"/>
</div>
</div>

<div class="form-group">
<div class="row">
<div class="col-xs-4">
</div>
<div class="col-xs-4">
<input type="submit" id="saveEmployee" class="btn btn-primary" value="Save" onclick="return submitEmployeeForm();"/>
</div>
<div class="col-xs-4">
</div>
</div>
</div>

</form:form>
</div>
</div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>

<script type="text/javascript">
function submitEmployeeForm() {

// getting the employee form values
var name = $('#name').val().trim();
var age = $('#age').val();
var salary = $('#salary').val();
if(name.length ==0) {
alert('Please enter name');
$('#name').focus();
return false;
}

if(age <= 0) {
alert('Please enter proper age');
$('#age').focus();
return false;
}

if(salary <= 0) {
alert('Please enter proper salary');
$('#salary').focus();
return false;
}
return true;
};
</script>
</body>
</html>
Run the above Program:



     Searching Employee data:



Happy Learning!