JAVA EXAMPLE PROGRAMS

JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Simple spring JDBC example


This page gives simple JDBC example using spring. We are using MySQL database here.

pom.xml file gives all required dependencies:

<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>SpringHelloWorld</groupId>
	<artifactId>SpringHelloWorld</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<properties>
		<spring.version>3.2.0.RELEASE</spring.version>
	</properties>
	<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-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.31</version>
		</dependency>
	</dependencies>
</project>

Employee model class:

package com.java2novice.model;

public class Employee {

	private int empId;
	private String name;
	private int salary;
	private String dept;
	
	public int getEmpId() {
		return empId;
	}
	public void setEmpId(int empId) {
		this.empId = empId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getSalary() {
		return salary;
	}
	public void setSalary(int salary) {
		this.salary = salary;
	}
	public String getDept() {
		return dept;
	}
	public void setDept(String dept) {
		this.dept = dept;
	}
}

Employee DAO interface:

package com.java2novice.dao;

import com.java2novice.model.Employee;

public interface EmployeeDao {

	public Employee findEmployeeById(int empId);
}

Employee DAO implementation class:

package com.java2novice.dao;

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

import javax.sql.DataSource;

import com.java2novice.model.Employee;

public class EmployeeDaoImpl implements EmployeeDao{

	private DataSource dataSource;
	 
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	@Override
	public Employee findEmployeeById(int empId) {
		
		Employee emp = null;
		String query = "select * from employee where emp_id=?"; 
		Connection conn = null;
		PreparedStatement prepStmt = null;
		ResultSet rsltSet = null;
		try {
			conn = dataSource.getConnection();
			prepStmt = conn.prepareStatement(query);
			prepStmt.setInt(1, empId);
			rsltSet = prepStmt.executeQuery();
			emp = new Employee();
			while(rsltSet.next()){
				emp.setEmpId(empId);
				emp.setName(rsltSet.getString("name"));
				emp.setSalary(rsltSet.getInt("salary"));
				emp.setDept(rsltSet.getString("dept"));
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				if(rsltSet != null) rsltSet.close();
				if(prepStmt != null) prepStmt.close();
			} catch(Exception ex){}
		}
		return emp;
	}

}

Here is the xml based configuration file, look at mysql DB configurations:

<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="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://localhost:3306/java2novice" />
		<property name="username" value="user_name" />
		<property name="password" value="password" />
	</bean>
	
    <bean id="employeeDAO" class="com.java2novice.dao.EmployeeDaoImpl">
		<property name="dataSource" ref="dataSource" />
	</bean>
</beans>

Here is the final demo class:

package com.java2novice.test;

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

import com.java2novice.dao.EmployeeDao;
import com.java2novice.model.Employee;

public class SpringDemo {

	public static void main(String a[]){
		
		String confFile = "applicationContext.xml";
		ConfigurableApplicationContext context = 
									new ClassPathXmlApplicationContext(confFile);
		EmployeeDao empDao = (EmployeeDao) context.getBean("employeeDAO");
		Employee emp = empDao.findEmployeeById(1);
		System.out.println(emp.getName()+" | "+emp.getSalary()+" | "+emp.getDept());
	}
}

Output:
nataraj | 20000 | Accounts
<< Previous Program | Next Program >>

Spring framework examples

  1. Spring 3 hello world example
  2. Spring bean java based configuration using @Configuration and @Bean
  3. How to get spring application context object reference?
  4. How to load multiple spring bean configuration files?
  5. Spring java based configuration @Import example
  6. Spring Dependency Injection and Types
  7. Spring Dependency Injection via setter method
  8. Spring Dependency Injection via Constructor
  9. Constructor overloading issue with spring constructor injection
  10. Constructor vs Setter dependency Injection in Spring
  11. How to inject value into spring bean instance variables?
  12. Spring bean tag properties
  13. Differen types of spring bean scopes
  14. How to inject inner bean in spring?
  15. Set spring bean scope using annotation
  16. How to invoke spring bean init and destroy methods?
  17. Spring bean initialization callback
  18. Spring bean destruction callback
  19. Configure default initialization and destroy method in all spring beans
  20. Spring bean init and destroy methods using annotations
  21. Spring Bean Post Processors
  22. How to read property file in spring using xml based configuration file?
  23. How to read property file in spring 3.0 using java based configuration?
  24. How to inject date into spring bean property?
  25. How to inject date into spring bean with CustomDateEditor?
  26. Spring bean inheritance configuration
  27. Spring dependency checking with @Required annotation
  28. How to define a custom Required-style annotation for dependency checking?
  29. How to inject List into spring bean?
  30. How to inject Set into spring bean?
  31. How to inject Map into spring bean?
  32. How to enable auto component scanning in spring?
  33. Difference between @Component, @Service, @Repository and @Controller
  34. How to filter components in auto scanning?
  35. Spring expression language basic example using xml based configuration.
  36. Spring expression language basic example using annotations.
  37. Bean reference example using spring expression language
  38. Spring expression language operators example
  39. Spring expression language ternary operator example
  40. How to use regular expressions with spring expression language?
  41. How to use collections with spring expression language?
  42. Spring bean auto-wiring modes
  43. Spring auto-wiring mode byName
  44. Spring auto-wiring mode byType
  45. Spring auto-wiring mode constructor
  46. Spring auto-wiring using @Autowired annotation example
  47. Spring auto-wiring using @Qualifier annotation example
  48. Spring log4j configuration
  49. How to schedule jobs using @Scheduled annotation in spring?
  50. Send E-mail using spring 3
  51. Send E-mail with attachment using spring 3
  52. Simple spring JDBC example
  53. Spring JDBC example with JdbcTemplate
  54. Spring JDBC example with JdbcDaoSupport
  55. Spring JDBC query example using JdbcDaoSupport
  56. How to query single column using spring JdbcTemplate?
  57. Spring JDBC batch updates using JdbcTemplate?
  58. Spring AOP Advices - Before advice example - xml based configuration
  59. Spring AOP Advices - After returning advice example - xml based configuration
  60. Spring AOP Advices - After throwing advice example - xml based configuration
  61. Spring AOP Advices - Around advice example - xml based configuration
  62. Spring AOP Advice - Pointcuts – Name match example
  63. Spring AOP Advice - Pointcuts – Regular expression example
  64. Spring AOP - AspectJ - @Before example
  65. Spring AOP - AspectJ - @After example
  66. Spring AOP - AspectJ - @AfterReturning example
  67. Spring AOP - AspectJ - @AfterThrowing example
  68. Spring AOP - AspectJ - @Around example
Knowledge Centre
Interface and its usage
Interface is similar to a class which may contain method's signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it. Interfaces are useful for declaring methods that one or more classes are expected to implement, capturing similarities between unrelated classes without forcing a class relationship and determining an object's programming interface without revealing the actual body of the class.
Famous Quotations
Be yourself; everyone else is already taken.
-- Oscar Wilde

About Author

I'm Nataraja Gootooru, programmer by profession and passionate about technologies. All examples given here are as simple as possible to help beginners. The source code is compiled and tested in my dev environment.

If you come across any mistakes or bugs, please email me to [email protected].

Most Visited Pages

Other Interesting Sites

Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle.
Privacy Policy | Copyright © 2022 by Nataraja Gootooru. All Rights Reserved.