Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Spring: Data access with JDBCTemplate

Spring provides a template class called JdbcTemplate that makes it easy to work with SQL relational databases and JDBC. Most JDBC code is mired in resource acquisition, connection management, exception handling, and general error checking that is wholly unrelated to what the code is meant to achieve. The JdbcTemplate takes care of all of that for you. All you have to do is focus on the task at hand.

In our earlier tutorial we have seen about Spring JDBC with simple example. Lets take same example for this tutorial and will implement separate method called insertByJDBCTemplate() which uses Spring JDBCTemplate to insert a record.

pom.xml remains same

Employee.java remains same

EmpDao.java

package com.app.dao;

import com.app.model.Employee;

public interface EmpDao {

 public void insert(Employee emp);
 public void insertByJDBCTemplate(Employee emp);
 
}


EmpDaoImpl.java

package com.app.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.jdbc.core.JdbcTemplate;

import com.app.model.Employee;

public class EmpDaoImpl implements EmpDao {

 
 private DataSource dataSource;
 private JdbcTemplate jdbcTemplate;
 
 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }
  
 public void insert(Employee emp) {
 
  String query = "INSERT INTO employee (id, empname, designation) VALUES (?, ?, ?)";
  Connection con = null;
 
  try {
   con = dataSource.getConnection();
   PreparedStatement ps = con.prepareStatement(query);
   ps.setInt(1, emp.getId());
   ps.setString(2, emp.getEmpName());
   ps.setString(3, emp.getDesignation());
   ps.executeUpdate();
   ps.close();
 
  } catch (SQLException e) {
   throw new RuntimeException(e);
 
  } finally {
   if (con != null) {
    try {
     con.close();
    } catch (SQLException e) {}
   }
  }  
 }
 
 
 
 public void insertByJDBCTemplate(Employee emp) {
  
  String query = "INSERT INTO employee (id, empname, designation) VALUES (?, ?, ?)";
  
  jdbcTemplate = new JdbcTemplate(dataSource);
   
  jdbcTemplate.update(query, new Object[] { emp.getId(), emp.getEmpName(), emp.getDesignation() });
 }
}


MyTestClass.java

package com.app;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.app.dao.EmpDao;
import com.app.model.Employee;

public class MyTestClass {

 public static void main(String[] args) {
  
  ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring-jdbc.xml");

  EmpDao object = appContext.getBean(EmpDao.class);
  
  Employee emp = new Employee(10011, "Steve", "CEO");
  
  //object.insert(emp);
  object.insertByJDBCTemplate(emp);
  
  appContext.close();
 }
}


OUTPUT:

Spring: Data access with JDBCTemplate



Spring: Data access with JDBC simple example

In our earlier tutorial we have seen about Spring + Hibernate with simple example. Now lets see sample example with Spring JDBC by using DataSource. For more notes on Spring JDBC you can refer to spring doc link.
Here we used MySql database to demonstrate this 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>com.app.spring.datasource</groupId>
  <artifactId>springdatasource</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <dependencies>
  
   <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.1.6.RELEASE</version>
 </dependency>
   <dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
  <version>5.1.35</version>
 </dependency>
   <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-jdbc</artifactId>
  <version>4.1.6.RELEASE</version>
 </dependency>
   
  </dependencies>
  
</project>


Employee.java

package com.app.model;

public class Employee {
 
 private int id;
 
 private String empName;
 
 private String designation;
 
 public Employee(int id, String empName, String designation){
  this.id = id;
  this.empName = empName;
  this.designation = 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;
 }  
}


EmpDao.java  

package com.app.dao;

import com.app.model.Employee;

public interface EmpDao {

 public void insert(Employee emp);
 
}


EmpDaoImpl.java

package com.app.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;

import com.app.model.Employee;

public class EmpDaoImpl implements EmpDao {

 
 private DataSource dataSource;
  
 public void setDataSource(DataSource dataSource) {
  this.dataSource = dataSource;
 }
  
 public void insert(Employee emp) {
 
  String query = "INSERT INTO employee (id, empname, designation) VALUES (?, ?, ?)";
  Connection con = null;
 
  try {
   con = dataSource.getConnection();
   PreparedStatement ps = con.prepareStatement(query);
   ps.setInt(1, emp.getId());
   ps.setString(2, emp.getEmpName());
   ps.setString(3, emp.getDesignation());
   ps.executeUpdate();
   ps.close();
 
  } catch (SQLException e) {
   throw new RuntimeException(e);
 
  } finally {
   if (con != null) {
    try {
     con.close();
    } catch (SQLException e) {}
   }
  }  
 }
}


spring-jdbc.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-4.1.xsd">

 
 <bean id="dataSource"
  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 
  <property name="driverClassName" value="com.mysql.jdbc.Driver" />
  <property name="url" value="jdbc:mysql://localhost:3306/roboticapp" />
  <property name="username" value="root" />
  <property name="password" value="root" />
 </bean>
 
 <bean id="empDS" class="com.app.dao.EmpDaoImpl">
  <property name="dataSource" ref="dataSource" />
 </bean>
 
</beans>


MyTestClass.java

package com.app;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.app.dao.EmpDao;
import com.app.model.Employee;

public class MyTestClass {

 public static void main(String[] args) {
  
  ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring-jdbc.xml");

  EmpDao object = appContext.getBean(EmpDao.class);
  
  Employee emp = new Employee(100, "Mark", "Manager");
  
  object.insert(emp);
  
  appContext.close();
 }
}


OUTPUT:
spring-Data access with JDBC simple example




Spring: Data access with JDBC simple example


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




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.

Spring with Hibernate simple example using Injection

We all know that Spring framework is a widely used framework along with popular ORM tool Hibernate. IN this tutorial lets see simple Spring example with Hibernate integration using Injection. Here we used Spring 4 integrate with Hibernate 4 with annotation based for demonstration. Best thing here we can use old version Hibernate 3 also by both xml and annotation based.  Just need to make sure that pom.xml and spring.xml are properly edited. 
Spring with Hibernate simple example using Injection


pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
 xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
 <modelVersion>4.0.0</modelVersion>
 <groupId>com.app.sphiber</groupId>
 <artifactId>springhibernate</artifactId>
 <packaging>war</packaging>
 <version>1.0-SNAPSHOT</version>
 <name>spring hibernate</name>

 <properties>
  <java.version>1.6</java.version>
  <spring-framework.version>4.0.3.RELEASE</spring-framework.version>
  <hibernate.version>4.3.5.Final</hibernate.version>
  <logback.version>1.0.13</logback.version>
  <slf4j.version>1.7.5</slf4j.version>
 </properties>

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

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

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

  <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>5.1.9</version>
  </dependency>
  <dependency>
   <groupId>commons-dbcp</groupId>
   <artifactId>commons-dbcp</artifactId>
   <version>1.4</version>
  </dependency>
  
  <dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
   <version>${slf4j.version}</version>
   <scope>compile</scope>
  </dependency>
  <dependency>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-classic</artifactId>
   <version>${logback.version}</version>
   <scope>runtime</scope>
  </dependency>
 </dependencies>
 
 <build>
  <finalName>springhibernate</finalName>  
 </build>

</project>




spring.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
 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/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
  http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">

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


 <bean id="hibernateSessionFac"
  class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource" />
  <property name="annotatedClasses">
   <list>
    <value>com.app.sphiber.model.Employee</value>
   </list>
  </property>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
    <prop key="hibernate.format_sql">false</prop>
    <prop key="hibernate.show_sql">true</prop>
   </props>
  </property>
 </bean>

 
 <bean id="empDao" class="com.app.sphiber.dao.EmpDaoImpl">
  <property name="sessionFactory" ref="hibernateSessionFac" />
 </bean>
</beans>




Employee.java

package com.app.sphiber.model;

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;
 } 
}




EmpDao.java

package com.app.sphiber.dao;

import java.util.List;

import com.app.sphiber.model.Employee;

public interface EmpDao {

 public List<Employee> findByUserName(String empName);
 
 public List<Employee> getAllEmployees();
 
 public void save(Employee emp);
}




EmpDaoImpl.java

package com.app.sphiber.dao;

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

import com.app.sphiber.model.Employee;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


@Component
public class EmpDaoImpl implements EmpDao{
 
 private SessionFactory sessionFactory;
 
 @Autowired
 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }
 
 
 @SuppressWarnings("unchecked")
 @Override
 public List<Employee> findByUserName(String empName) {
  
  List<Employee> emp = new ArrayList<Employee>();
  Session session = null;
  session = this.sessionFactory.openSession();
  session.beginTransaction();  
  String qry = "from Employee where empName = '"+empName+"'";
  Query query = session.createQuery(qry);
  emp = query.list();
  session.close();
  
  return emp;

 }
 
 @Override
 public void save(Employee emp) {
  Session session = null;
  session = sessionFactory.openSession();
  session.beginTransaction();
  session.save(emp);
  session.getTransaction().commit();
  session.close();  
 }

 @SuppressWarnings("unchecked")
 @Override
 public List<Employee> getAllEmployees() {
  List<Employee> emp = new ArrayList<Employee>();
  Session session = null;
  session = this.sessionFactory.openSession();
  session.beginTransaction();  
  String qry = "from Employee";
  Query query = session.createQuery(qry);
  emp = query.list();
  session.close();
  
  return emp;
 }
}




MyTestClass.java

package com.app.sphiber;

import java.util.ArrayList;
import java.util.List;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.app.sphiber.dao.EmpDao;
import com.app.sphiber.model.Employee;

public class MyTestClass {

 public static void main(String[] args) {
  
  ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("spring.xml");

  EmpDao dao = appContext.getBean(EmpDao.class);
  
  Employee emp = new Employee();
  emp.setId(10);
  emp.setEmpName("Steve");
  emp.setDesignation("COO");
  dao.save(emp);
  
  List<Employee> list = new ArrayList<Employee>();
  list = dao.findByUserName("Steve");
  for (Employee employee : list) {
   System.out.println("DESIGNATION : "+ employee.getDesignation());
  }
  
  
  List<Employee> list1 = new ArrayList<Employee>();
  list1 = dao.getAllEmployees();
  for (Employee employee : list1) {
   System.out.println("EMP NAME : "+ employee.getDesignation());
  }
  
  
  appContext.close();
 }
}




Spring with Hibernate simple example using Injection

Also you can download complete project code in this link.