Friday, 29 May 2015

Spring: Constructor Injection by Example

In our last tutorial we have seen about Setter Injection by simple example. In this tutorial we see same example with Constructor Injection. Only thing which we need to take care is "constructor-arg" order and type should match with bean class constructor method. Otherwise constructor injection argument type ambiguities exception will be thrown.
Dependency Injection with Spring


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>org.springframework.samples</groupId>
 <artifactId>SimpleSetterInj</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <dependencies>
  <!-- Spring Core -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>3.2.10.RELEASE</version>
  </dependency>
 </dependencies>
</project>


Employee.java

package com.app.springcore;

public class Employee {

 private String empName;
 private int age;
 private String gender;

 public Employee(String empName, int age, String gender){
  this.empName = empName;
  this.age = age;
  this.gender = gender;
 } 
 public String getEmpName() {
  return empName;
 }
 public int getAge() {
  return age;
 }
 public String getGender() {
  return gender;
 }
}


Office.java

package com.app.springcore;

public class Office {

 private String offName;
 private String offAddress;
 private Employee employee;
 
 public Office(String offName, String offAddress, Employee employee){
  this.offName = offName;
  this.offAddress = offAddress;
  this.employee = employee;
 }
 
 public String getOffName() {
  return offName;
 }
 public String getOffAddress() {
  return offAddress;
 }
 public Employee getEmployee() {
  return employee;
 }
}


Spring-Core.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    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">
 
    <bean id="emp" class="com.app.springcore.Employee">
     
     <constructor-arg><value>Steve</value></constructor-arg>
   <constructor-arg><value>35</value></constructor-arg>
   <constructor-arg><value>Male</value></constructor-arg>
        
    </bean>
 
    <bean id="office" class="com.app.springcore.Office">
        <constructor-arg><value>ABCD Crop.</value></constructor-arg>
   <constructor-arg><value>Bangalore, India</value></constructor-arg>
   <constructor-arg ref="emp"></constructor-arg>
  </bean>
 
</beans>


TestClass.java

package com.app.springcore;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestClass {

 public static void main(String[] args) {
  ApplicationContext appCon = new ClassPathXmlApplicationContext("Spring-Core.xml");
  Office office = (Office)appCon.getBean("office");
  
  System.out.println("Office Name    : "+office.getOffName());
  System.out.println("Office Address : "+office.getOffAddress());
  System.out.println("Employee Name  : "+office.getEmployee().getEmpName());
  System.out.println("Employee Age   : "+office.getEmployee().getAge());
  System.out.println("Employee Gender: "+office.getEmployee().getGender());
  
  ((ConfigurableApplicationContext)appCon).close();
        }
}


OUTPUT:

Office Name    : ABCD Crop.
Office Address : Bangalore, India
Employee Name  : Steve
Employee Age   : 35
Employee Gender: Male
Spring: Constructor Injection by Example




read more.. "Spring: Constructor Injection by Example"

Spring: Setter Injection by Example

Core of the Spring Framework is its Inversion of Control (Ioc) container. The IoC container manages java objects – from instantiation to destruction – through its BeanFactory. Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean's scope, life-cycle events, and any AOP features.
Dependency Injection with Spring
The IoC container enforces the dependency injection pattern for components by leaving them loosely coupled and allowed to code to abstractions. It exits in two major types like

  • Setter Injection
  • Constructor Injection

In this tutorial lets discuss about Setter Injection with simple example

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>org.springframework.samples</groupId>
 <artifactId>SimpleSetterInj</artifactId>
 <version>0.0.1-SNAPSHOT</version>

 <dependencies>
  <!-- Spring Context -->
  <dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-context</artifactId>
   <version>3.2.10.RELEASE</version>
  </dependency>
 </dependencies>
</project>


Employee.java

package com.app.springcore;

public class Employee {

 private String empName;
 private int age;
 private String gender;
 
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public String getGender() {
  return gender;
 }
 public void setGender(String gender) {
  this.gender = gender;
 }
}


Office.java

package com.app.springcore;

public class Office {

 private String offName;
 private String offAddress;
 private Employee employee;
 
 public String getOffName() {
  return offName;
 }
 public void setOffName(String offName) {
  this.offName = offName;
 }
 public String getOffAddress() {
  return offAddress;
 }
 public void setOffAddress(String offAddress) {
  this.offAddress = offAddress;
 }
 public Employee getEmployee() {
  return employee;
 }
 public void setEmployee(Employee employee) {
  this.employee = employee;
 }
}


Spring-Core.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    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">
 
    <bean id="emp" class="com.app.springcore.Employee">
        <property name="empName" value="Steve"></property>
        <property name="age"><value>35</value> </property>
        <property name="gender" value="Male"></property>
    </bean>
 
    <bean id="office" class="com.app.springcore.Office">
        <property name="offName" value="ABCD Crop."></property>
        <property name="offAddress" value="Bangalore, India"></property>
        <property name="employee" ref="emp"></property>
    </bean>
 
</beans>


TestClass.java

package com.app.springcore;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestClass {

 public static void main(String[] args) {
  ApplicationContext appCon = new ClassPathXmlApplicationContext("Spring-Core.xml");
  Office office = (Office)appCon.getBean("office");
  
  System.out.println("Office Name    : "+office.getOffName());
  System.out.println("Office Address : "+office.getOffAddress());
  System.out.println("Employee Name  : "+office.getEmployee().getEmpName());
  System.out.println("Employee Age   : "+office.getEmployee().getAge());
  System.out.println("Employee Gender: "+office.getEmployee().getGender());
  
  ((ConfigurableApplicationContext)appCon).close();
        }
}


OUTPUT:

Office Name    : ABCD Crop.
Office Address : Bangalore, India
Employee Name  : Steve
Employee Age   : 35
Employee Gender: Male



You can download sample project in this link.

read more.. "Spring: Setter Injection by Example "

Tuesday, 26 May 2015

JSON Date Format

When we pass formatted date through JSON the conversion won't to same as we required. So we need to use @JsonSerialize annotation to get out customized date format. Below example shows with and without @JsonSerialize annotation and its output. Here we used Spring rest to demonstrate with response type as JSON.

Employee model class which contains date field.

Employee.java
import java.util.Date;

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

public class Employee {

 private int id;
 private String empName;
 private Date doj;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public Date getDoj() {
  return doj;
 }
 
 public void setDoj(Date doj) {
  this.doj = doj;
 } 
}


Spring rest controller class.
MyController.java
import java.util.Date;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.models.Employee;

@RestController
public class MyController {

 @RequestMapping(value="/getemp", method=RequestMethod.GET, headers="Accept=application/json")
 public ResponseEntity<Employee> getEmpDetails(){
  
  Employee emp = new Employee();
  emp.setId(1);
  emp.setEmpName("Steve");
  emp.setDoj(new Date());
  
  return new ResponseEntity<Employee>(emp, HttpStatus.OK);
 }
}


OUTPUT:
JSON Date Format


IN above example we see that DOJ date conversion to default date format is wrong. So we need to set @JsonSerialize annotation to get our date conversion correctly as like below example.

JSON custom date formatting class
CustomDateSerializer.java
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

public class CustomDateSerializer extends JsonSerializer<Date> {

 @Override
    public void serialize(Date date, JsonGenerator jGen, SerializerProvider arg2) throws 
        IOException, JsonProcessingException {      

        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm:ss");
        String fDate = sdf.format(date);

        jGen.writeString(fDate);
    }
}


Employee model class with @JsonSerialize annotation. Just add below given annotation before "doj" setter method.
Employee.java
@JsonSerialize(using = CustomDateSerializer.class)
 public void setDoj(Date doj) {
  this.doj = doj;
 } 


OUTPUT:
JSON Date Format



read more.. "JSON Date Format"

Monday, 25 May 2015

Hibernate: Simple Example

Hibernate is a powerful ORM tool which makes developers life very easy. As we all read that Hibernate comes with its own session and transaction management features and also as a Java developer its not mandatory to have SQL knowledge. In below example we are going to see simple example with Employee class where we used to do operations like Create, Update, Read and Delete (CURD). For demo purpose we use MySQL connector and Hibernate 3 version.
Hibernate - Simple Example.png


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.app.hiber</groupId>
 <artifactId>hibernatesample</artifactId>
 <packaging>war</packaging>
 <version>0.0.1-SNAPSHOT</version>
 <name>Hibernate Sample</name>
 <description>Hibernate sample application</description>

 <dependencies>

  <!-- MySQL database driver -->

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.9</version>
   </dependency>

  <!-- Hibernate framework -->

  <dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-core</artifactId>
   <version>3.6.3.Final</version>
  </dependency>

  <dependency>
   <groupId>javassist</groupId>
   <artifactId>javassist</artifactId>
   <version>3.12.1.GA</version>
  </dependency>
 </dependencies>

 <properties>
  <java.version>1.6</java.version>  
 </properties>

</project>


hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>

<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>

        <!-- Database connection settings -->
   <!--  Mysql Setting -->
   <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/roboticapp</property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
   
   <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">1</property>

        <!-- SQL dialect -->
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  
  
        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <!-- Names the annotated entity class -->
        <mapping class="com.app.hiber.models.Employee"/>
        
        
    </session-factory>

</hibernate-configuration>


Employee.java
package com.app.hiber.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
 
@Entity
@Table(name="employee")
public class Employee {

 @Id 
 private int id;
 
 @Column(name="empname")
 private String empName;
 
 @Column(name="designation")
 private String designation;
 
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public String getDesignation() {
  return designation;
 }
 public void setDesignation(String designation) {
  this.designation = designation;
 } 
}


DBCon.java
package com.app.hiber.dao;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;


public class DBCon {
 
 private static SessionFactory factory = null;
 
 private DBCon(){}
 
 public static SessionFactory getSessionFactory(){
  synchronized (DBCon.class) {
   if(factory == null){
    factory=new Configuration().configure().buildSessionFactory();    
   }
  }  
  return factory;
 }
}


EmpService.java
package com.app.hiber.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;

import com.app.hiber.models.Employee;

public class EmpService {
 
 private SessionFactory factory = null;
 
 public EmpService() {
  this.factory = DBCon.getSessionFactory();
 }
 
 public void addEmployee(Employee emp){
  Session session = null;
  try{
   session = factory.openSession();
   session.beginTransaction();
   
   session.save(emp);
   
   session.getTransaction().commit();

  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(session != null) session.close();
  }  
 }
 
 public void updateEmployee(String name, int id){
  
  Session session = null;
  try{
   
   session = factory.openSession();
   session.beginTransaction();
   String hql = "UPDATE Employee SET empName = :name WHERE id = :id";
   
   Query query = session.createQuery(hql);
   query.setParameter("name", name);
   query.setParameter("id", id);
   
   int result = query.executeUpdate();
   session.getTransaction().commit();
 
   System.out.println("Rows affected : " + result);
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(session != null) session.close();
  }
 }
 
 
 @SuppressWarnings("unchecked")
 public List<Employee> readEmployee(int id){
  List<Employee> list = new ArrayList<Employee>();
  Session session = null;
  try{
   
   session = factory.openSession();
   session.beginTransaction();
   String hql = "FROM Employee WHERE id = "+id;
   
   Query query = session.createQuery(hql);
   
   list = query.list();
 
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(session != null) session.close();
  }
  return list;
 }
 
 public void deleteEmployee(int id){
  
  Session session = null;
  try{
   
   session = factory.openSession();
   session.beginTransaction();
   String hql = "DELETE FROM Employee WHERE id = :id";
   
   Query query = session.createQuery(hql);
   query.setParameter("id", id);
   
   int result = query.executeUpdate();
   session.getTransaction().commit();
 
   System.out.println("Rows affected : " + result);
  }catch(Exception e){
   e.printStackTrace();
  }finally{
   if(session != null) session.close();
  }
 }
}


DemoTest.java
package com.app.hiber;

import java.util.List;

import com.app.hiber.dao.EmpService;
import com.app.hiber.models.Employee;

public class DemoTest {

 public static void main(String[] args) {
  
  Employee emp = new Employee();
  emp.setId(1000);
  emp.setEmpName("James");
  emp.setDesignation("CEO");
  
  //Create
  EmpService eSer = new EmpService();
  eSer.addEmployee(emp);
  
  //Update 
  eSer.updateEmployee("James 007", 1000);
  
  //Read
  List<Employee> list = eSer.readEmployee(1000);
  System.out.println(list.get(0).getEmpName());
  
  
  //Delete
  eSer.deleteEmployee(1000);
  
 }
}

Hibernate: Simple Example

Sample project can be download from this link.

read more.. "Hibernate: Simple Example"