This is a tutorial of Spring JDBC Framework. When we need to interface with databases the Spring JDBC framework provides solutions to all the low-level details, like open/close a connection, prepare and execute SQL statements, process exceptions and handle transactions. Thus, the only thing a developer must do is just define connection parameters and specify the SQL statement to be executed. Spring JDBC provides several approaches and different classes to form the basis for a JDBC database access. The most popular approach makes use of JdbcTemplate class. This is the central framework class that manages all the database communication and exception handling.
In order to work with JDBC in Spring we will make use of the Data Access Objects. DAOs in Spring are commonly used for database interaction, using data access technologies like JDBC, Hibernate, JPA or JDO in a consistent way. DAOs provide a means to read and write data to the database and they can expose this functionality through an interface by which the rest of the application can access them.Here, we shall begin by showing you a simple example of JDBC integration. We will use a simple DAO, to make a simple insert and select to a database. We will continue with examples of the JdbcTemplate class to make SQL operations even easier. We will make use of the methods JdbcTemplate class provides to perform various selects and updates to the database. Our preferred development environment is Eclipse. We are using Eclipse Juno (4.2) version, along with Maven Integration plugin version 3.1.0. You can download Eclipse from here and Maven Plugin for Eclipse from here. The installation of Maven plugin for Eclipse is out of the scope of this tutorial and will not be discussed. We are also using Spring version 3.2.3 and the JDK 7_u_21. The database used in the example is MySQL Database Server 5.6. Let’s begin, 1. Create a new Maven projectGo to File -> Project ->Maven -> Maven Project.
In the “Select project name and location” page of the wizard, make sure that “Create a simple project (skip archetype selection)” option is checked, hit “Next” to continue with default values.
In the “Enter an artifact id” page of the wizard, you can define the name and main package of your project. We will set the “Group Id” variable to "com.javacodegeeks.snippets.enterprise" and the “Artifact Id” variable to "springexample" . The aforementioned selections compose the main project package as "com.javacodegeeks.snippets.enterprise.springexample" and the project name as "springexample" . Hit “Finish” to exit the wizard and to create your project.
The Maven project structure is shown below:
It consists of the following folders:- /src/main/java folder, that contains source files for the dynamic content of the application,
- /src/test/java folder contains all source files for unit tests,
- /src/main/resources folder contains configurations files,
- /target folder contains the compiled and packaged deliverables,
- the pom.xml is the project object model (POM) file. The single file that contains all project related configuration.
2. Add Spring 3.2.3 dependency- Locate the “Properties” section at the “Overview” page of the POM editor and perform the following changes:
Create a new property with name org.springframework.version and value 3.2.3.RELEASE. - Navigate to the “Dependencies” page of the POM editor and create the following dependencies (you should fill the “GroupId”, “Artifact Id” and “Version” fields of the “Dependency Details” section at that page):
Group Id : org.springframework Artifact Id : spring-web Version : ${org.springframework.version}
Alternatively, you can add the Spring dependencies in Maven’s pom.xml file, by directly editing it at the “Pom.xml” page of the POM editor, as shown below: pom.xml: 03 | < modelVersion >4.0.0</ modelVersion > |
04 | < groupId >com.javacodegeeks.snippets.enterprise</ groupId > |
05 | < artifactId >springexample</ artifactId > |
06 | < version >0.0.1-SNAPSHOT</ version > |
10 | < groupId >org.springframework</ groupId > |
11 | < artifactId >spring-core</ artifactId > |
12 | < version >${spring.version}</ version > |
15 | < groupId >org.springframework</ groupId > |
16 | < artifactId >spring-context</ artifactId > |
17 | < version >${spring.version}</ version > |
22 | < spring.version >3.2.3.RELEASE</ spring.version > |
As you can see Maven manages library dependencies declaratively. A local repository is created (by default under {user_home}/.m2 folder) and all required libraries are downloaded and placed there from public repositories. Furthermore intra – library dependencies are automatically resolved and manipulated. 3. Add the JDBC dependenciesThe dependencies needed for Spring JDBC are the ones below: pom.xml 03 | < modelVersion >4.0.0</ modelVersion > |
04 | < groupId >com.javacodegeeks.snippets.enterprise</ groupId > |
05 | < artifactId >springexample</ artifactId > |
06 | < version >0.0.1-SNAPSHOT</ version > |
10 | < groupId >org.springframework</ groupId > |
11 | < artifactId >spring-core</ artifactId > |
12 | < version >${spring.version}</ version > |
15 | < groupId >org.springframework</ groupId > |
16 | < artifactId >spring-context</ artifactId > |
17 | < version >${spring.version}</ version > |
20 | < groupId >mysql</ groupId > |
21 | < artifactId >mysql-connector-java</ artifactId > |
22 | < version >5.1.26</ version > |
25 | < groupId >org.springframework</ groupId > |
26 | < artifactId >spring-jdbc</ artifactId > |
27 | < version >${spring.version}</ version > |
32 | < spring.version >3.2.3.RELEASE</ spring.version > |
4. Execute a simple insert and select exampleLet’s start, by creating a simple table in the database. We create a simple Employee table, that has three columns. The SQL statement that is executed in MySQL Workbench is shown below: Create a table 1 | CREATE TABLE `Employee` ( |
2 | `ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, |
3 | `NAME` VARCHAR(100) NOT NULL, |
4 | `AGE` INT(10) UNSIGNED NOT NULL, |
5 | PRIMARY KEY (`CUST_ID`) |
6 | ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8; |
We also create a class, Employee.java , that has three fields that are the same to the columns of Employee table. Employee.java 01 | package com.javacodegeeks.snippets.enterprise; |
03 | public class Employee { |
15 | public Employee( int id, String name, int age) { |
25 | public void setId( int id) { |
29 | public String getName() { |
33 | public void setName(String name) { |
41 | public void setAge( int age) { |
46 | public String toString() { |
47 | return Employee [ "id= " + id + ", name= " + name + ", age= " + age |
The DAO created to interact between the java class and the table is the EmployeeDAOImpl.java . It has two methods, insert(Employee employee) and findById(int id) , that implement the insert and select statements to the database. Both methods use the DataSource class, a utility class that provides connection to the database. It is part of the JDBC specification and allows a container or a framework to hide connection pooling and transaction management issues from the application code. In addition, both methods open a Connection to the database and use the PreparedStatement , that is an object representing a precompiled SQL statement. EmployeeDAO.java 1 | package com.javacodegeeks.snippets.enterprise.dao; |
3 | import com.javacodegeeks.snippets.enterprise.Employee; |
5 | public interface EmployeeDAO { |
7 | public void insert(Employee employee); |
8 | public Employee findById( int id); |
EmployeeDAOImpl.java 01 | package com.javacodegeeks.snippets.enterprise.dao.impl; |
03 | import java.sql.Connection; |
04 | import java.sql.PreparedStatement; |
05 | import java.sql.ResultSet; |
06 | import java.sql.SQLException; |
08 | import javax.sql.DataSource; |
10 | import com.javacodegeeks.snippets.enterprise.Employee; |
11 | import com.javacodegeeks.snippets.enterprise.dao.EmployeeDAO; |
13 | public class EmployeeDAOImpl implements EmployeeDAO |
15 | private DataSource dataSource; |
17 | public void setDataSource(DataSource dataSource) { |
18 | this .dataSource = dataSource; |
21 | public void insert(Employee employee){ |
23 | String sql = "INSERT INTO employee " + |
24 | "(ID, NAME, AGE) VALUES (?, ?, ?)" ; |
25 | Connection conn = null ; |
28 | conn = dataSource.getConnection(); |
29 | PreparedStatement ps = conn.prepareStatement(sql); |
30 | ps.setInt( 1 , employee.getId()); |
31 | ps.setString( 2 , employee.getName()); |
32 | ps.setInt( 3 , employee.getAge()); |
36 | } catch (SQLException e) { |
37 | throw new RuntimeException(e); |
43 | } catch (SQLException e) {} |
48 | public Employee findById( int id){ |
50 | String sql = "SELECT * FROM EMPLOYEE WHERE ID = ?" ; |
52 | Connection conn = null ; |
55 | conn = dataSource.getConnection(); |
56 | PreparedStatement ps = conn.prepareStatement(sql); |
58 | Employee employee = null ; |
59 | ResultSet rs = ps.executeQuery(); |
61 | employee = new Employee( |
70 | } catch (SQLException e) { |
71 | throw new RuntimeException(e); |
76 | } catch (SQLException e) {} |
The Datasource is configured in applicationContext.xml file. All parameters needed for the connection to the database are set here. It is defined in other bean definitions using the ref element. applicationContext.xml 09 | < bean id = "employeeDAO" class = "com.javacodegeeks.snippets.enterprise.dao.impl.EmployeeDAOImpl" > |
10 | < property name = "dataSource" ref = "dataSource" /> |
14 | class = "org.springframework.jdbc.datasource.DriverManagerDataSource" > |
16 | < property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> |
18 | < property name = "username" value = "root" /> |
19 | < property name = "password" value = "root" /> |
We can run the example, using the App.java class. We load the employeeBean and then create a new Employee object. We first insert it to the table and then make a select to find it. App.java 01 | package com.javacodegeeks.snippets.enterprise; |
03 | import org.springframework.context.ConfigurableApplicationContext; |
04 | import org.springframework.context.support.ClassPathXmlApplicationContext; |
06 | import com.javacodegeeks.snippets.enterprise.dao.EmployeeDAO; |
07 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
11 | public static void main(String[] args) { |
13 | ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml" ); |
14 | EmployeeDAO employeeDAO = (EmployeeDAO) context.getBean( "employeeDAO" ); |
15 | Employee employee1 = new Employee( 123 , "javacodegeeks" , 30 ); |
16 | employeeDAO.insert(employee1); |
17 | Employee employee2 = employeeDAO.findById( 123 ); |
18 | System.out.println(employee2); |
The output is shown below: Output Employee [id=123, name=javacodegeeks, age=30]
5. Use of JdbcTemplate ClassThe JdbcTemplate class executes SQL queries, update statements and stored procedure calls, performs iteration over ResultSets and extraction of returned parameter values. It handles the creation and release of resources, thus avoiding errors such as forgetting to close the connection. It also catches JDBC exceptions and translates them to the generic, more informative, exception hierarchy defined in the org.springframework.dao package. A simple insert example in JDBCEmployeeDAOImpl.java class, using the JdbcTemplate class is shown below: JDBCEmployeeDAO.java 1 | package com.javacodegeeks.snippets.enterprise.dao; |
3 | import com.javacodegeeks.snippets.enterprise.Employee; |
5 | public interface JDBCEmployeeDAO { |
7 | public void insert(Employee employee); |
JDBCEmployeeDAOImpl.java 01 | package com.javacodegeeks.snippets.enterprise.dao.impl; |
03 | import javax.sql.DataSource; |
05 | import org.springframework.jdbc.core.JdbcTemplate; |
07 | import com.javacodegeeks.snippets.enterprise.Employee; |
08 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
10 | public class JDBCEmployeeDAOImpl implements JDBCEmployeeDAO{ |
11 | private DataSource dataSource; |
12 | private JdbcTemplate jdbcTemplate; |
14 | public void setDataSource(DataSource dataSource) { |
15 | this .dataSource = dataSource; |
18 | public void insert(Employee employee){ |
20 | String sql = "INSERT INTO EMPLOYEE " + |
21 | "(ID, NAME, AGE) VALUES (?, ?, ?)" ; |
23 | jdbcTemplate = new JdbcTemplate(dataSource); |
25 | jdbcTemplate.update(sql, new Object[] { employee.getId(), |
26 | employee.getName(), employee.getAge() |
5.1 Select examplesNow, let’s see how to make use of the JdbcTemplate class to make select statements in different ways. We can add new queries in EmployeeDAOImpl.java class as shown in the following cases. 5.1.1 Select a single rowIn order to make a single row select we can implement the RowMapper interface. Thus, we can override the mapRow(ResultSet rs, int rowNum) method of RowMapper to map the table fields to the object, as shown below: EmployeeRowMapper.java 01 | package com.javacodegeeks.snippets.enterprise; |
03 | import java.sql.ResultSet; |
04 | import java.sql.SQLException; |
06 | import org.springframework.jdbc.core.RowMapper; |
08 | @SuppressWarnings ( "rawtypes" ) |
09 | public class EmployeeRowMapper implements RowMapper { |
10 | public Object mapRow(ResultSet rs, int rowNum) throws SQLException { |
11 | Employee employee = new Employee(); |
12 | employee.setId(rs.getInt( "ID" )); |
13 | employee.setName(rs.getString( "NAME" )); |
14 | employee.setAge(rs.getInt( "AGE" )); |
We add a new method findById(int id) to JDBCEmployeeDAO.java and JDBCEmployeeDAOImpl.java . Here, the queryForObject(String sql, Object[] args, RowMapper rowMapper) method of JDBCTemplate class will create the select with the given sql statement and the given id. It will then map the result that is a single row to the Employee object using the EmployeeRowMapper.java implementation. JDBCEmployeeDAO.java 01 | package com.javacodegeeks.snippets.enterprise.dao; |
03 | import com.javacodegeeks.snippets.enterprise.Employee; |
05 | public interface JDBCEmployeeDAO { |
07 | public void insert(Employee employee); |
08 | public Employee findById( int id); |
JDBCEmployeeDAOImpl.java 01 | package com.javacodegeeks.snippets.enterprise.dao.impl; |
03 | import javax.sql.DataSource; |
05 | import org.springframework.jdbc.core.JdbcTemplate; |
07 | import com.javacodegeeks.snippets.enterprise.Employee; |
08 | import com.javacodegeeks.snippets.enterprise.EmployeeRowMapper; |
09 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
11 | public class JDBCEmployeeDAOImpl implements JDBCEmployeeDAO{ |
12 | private DataSource dataSource; |
13 | private JdbcTemplate jdbcTemplate; |
15 | public void setDataSource(DataSource dataSource) { |
16 | this .dataSource = dataSource; |
19 | public void insert(Employee employee){ |
21 | String sql = "INSERT INTO EMPLOYEE " + |
22 | "(ID, NAME, AGE) VALUES (?, ?, ?)" ; |
24 | jdbcTemplate = new JdbcTemplate(dataSource); |
26 | jdbcTemplate.update(sql, new Object[] { employee.getId(), |
27 | employee.getName(), employee.getAge() |
31 | @SuppressWarnings ({ "unchecked" }) |
32 | public Employee findById( int id){ |
34 | String sql = "SELECT * FROM EMPLOYEE WHERE ID = ?" ; |
36 | jdbcTemplate = new JdbcTemplate(dataSource); |
37 | Employee employee = (Employee) jdbcTemplate.queryForObject( |
38 | sql, new Object[] { id }, new EmployeeRowMapper()); |
Another way to get a single result is to use the BeanPropertyRowMapper implementation of RowMapper that converts a row into a new instance of the specified mapped target class. The BeanPropertyRowMapper maps a row column value to a property of the object by matching their names. JDBCEmployeeDAOImpl.java 01 | package com.javacodegeeks.snippets.enterprise.dao.impl; |
03 | import javax.sql.DataSource; |
05 | import org.springframework.jdbc.core.BeanPropertyRowMapper; |
06 | import org.springframework.jdbc.core.JdbcTemplate; |
08 | import com.javacodegeeks.snippets.enterprise.Employee; |
09 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
11 | public class JDBCEmployeeDAOImpl implements JDBCEmployeeDAO{ |
12 | private DataSource dataSource; |
13 | private JdbcTemplate jdbcTemplate; |
15 | public void setDataSource(DataSource dataSource) { |
16 | this .dataSource = dataSource; |
19 | public void insert(Employee employee){ |
21 | String sql = "INSERT INTO EMPLOYEE " + |
22 | "(ID, NAME, AGE) VALUES (?, ?, ?)" ; |
24 | jdbcTemplate = new JdbcTemplate(dataSource); |
26 | jdbcTemplate.update(sql, new Object[] { employee.getId(), |
27 | employee.getName(), employee.getAge() |
31 | @SuppressWarnings ({ "unchecked" , "rawtypes" }) |
32 | public Employee findById( int id){ |
34 | String sql = "SELECT * FROM EMPLOYEE WHERE ID = ?" ; |
36 | jdbcTemplate = new JdbcTemplate(dataSource); |
37 | Employee employee = (Employee) jdbcTemplate.queryForObject( |
38 | sql, new Object[] { id }, new BeanPropertyRowMapper(Employee. class )); |
We add the jdbcEmployeeDAOBean to applicationContext.xml : applicationContext.xml 09 | < bean id = "employeeDAO" class = "com.javacodegeeks.snippets.enterprise.dao.impl.EmployeeDAOImpl" > |
10 | < property name = "dataSource" ref = "dataSource" /> |
13 | < bean id = "jdbcEmployeeDAO" class = "com.javacodegeeks.snippets.enterprise.dao.impl.JDBCEmployeeDAOImpl" > |
14 | < property name = "dataSource" ref = "dataSource" /> |
18 | class = "org.springframework.jdbc.datasource.DriverManagerDataSource" > |
20 | < property name = "driverClassName" value = "com.mysql.jdbc.Driver" /> |
22 | < property name = "username" value = "root" /> |
23 | < property name = "password" value = "root" /> |
After loading the new bean to App.java class we can call its methods, as shown below: App.java 01 | package com.javacodegeeks.snippets.enterprise; |
03 | import org.springframework.context.ConfigurableApplicationContext; |
04 | import org.springframework.context.support.ClassPathXmlApplicationContext; |
06 | import com.javacodegeeks.snippets.enterprise.dao.EmployeeDAO; |
07 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
11 | public static void main(String[] args) { |
13 | ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml" ); |
15 | JDBCEmployeeDAO jdbcEmployeeDAO = (JDBCEmployeeDAO) context.getBean( "jdbcEmployeeDAO" ); |
16 | Employee employee3 = new Employee( 456 , "javacodegeeks" , 34 ); |
17 | jdbcEmployeeDAO.insert(employee3); |
19 | Employee employee4 = jdbcEmployeeDAO.findById( 456 ); |
20 | System.out.println(employee4); |
The output is the one below: Output Employee [id=456, name=javacodegeeks, age=34]
5.1.2 Select total rowsNow, we can query for total number of rows in the database. Again, there are two ways to map the Result . The easiest way is to use the BeanPropertyRowMapper , as shown in the example above, but another way is to create our own mapping. We add a new method to query in JDBCEmployeeDAOImpl.java class. The new method is List<Employee> findAll() , and it uses the queryForInt(String sql) method of JdbcTemplate class execute the query, as shown below: JDBCEmployeeDAO.java 01 | package com.javacodegeeks.snippets.enterprise.dao; |
05 | import com.javacodegeeks.snippets.enterprise.Employee; |
07 | public interface JDBCEmployeeDAO { |
09 | public void insert(Employee employee); |
10 | public Employee findById( int id); |
11 | public List<Employee> findAll(); |
JDBCEmployeeDAOImpl.java 01 | package com.javacodegeeks.snippets.enterprise.dao.impl; |
03 | import java.util.ArrayList; |
07 | import javax.sql.DataSource; |
09 | import org.springframework.jdbc.core.BeanPropertyRowMapper; |
10 | import org.springframework.jdbc.core.JdbcTemplate; |
12 | import com.javacodegeeks.snippets.enterprise.Employee; |
13 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
15 | public class JDBCEmployeeDAOImpl implements JDBCEmployeeDAO{ |
16 | private DataSource dataSource; |
17 | private JdbcTemplate jdbcTemplate; |
19 | public void setDataSource(DataSource dataSource) { |
20 | this .dataSource = dataSource; |
23 | public void insert(Employee employee){ |
25 | String sql = "INSERT INTO EMPLOYEE " + |
26 | "(ID, NAME, AGE) VALUES (?, ?, ?)" ; |
28 | jdbcTemplate = new JdbcTemplate(dataSource); |
30 | jdbcTemplate.update(sql, new Object[] { employee.getId(), |
31 | employee.getName(), employee.getAge() |
35 | @SuppressWarnings ({ "unchecked" , "rawtypes" }) |
36 | public Employee findById( int id){ |
38 | String sql = "SELECT * FROM EMPLOYEE WHERE ID = ?" ; |
40 | jdbcTemplate = new JdbcTemplate(dataSource); |
41 | Employee employee = (Employee) jdbcTemplate.queryForObject( |
42 | sql, new Object[] { id }, new BeanPropertyRowMapper(Employee. class )); |
47 | @SuppressWarnings ( "rawtypes" ) |
48 | public List<Employee> findAll(){ |
50 | jdbcTemplate = new JdbcTemplate(dataSource); |
51 | String sql = "SELECT * FROM EMPLOYEE" ; |
53 | List<Employee> employees = new ArrayList<Employee>(); |
55 | List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); |
56 | for (Map row : rows) { |
57 | Employee employee = new Employee(); |
58 | employee.setId(Integer.parseInt(String.valueOf(row.get( "ID" )))); |
59 | employee.setName((String)row.get( "NAME" )); |
60 | employee.setAge(Integer.parseInt(String.valueOf(row.get( "AGE" )))); |
61 | employees.add(employee); |
5.1.3 Select a single columnTo get a specified column name we create a new method, String findNameById(int id) , where we use the queryForObject(String sql, Object[] args, Class<String> requiredType) method of JdbcTemplate class. In this method we can set the type of the column that the query will return. JDBCEmployeeDAO.java 01 | package com.javacodegeeks.snippets.enterprise.dao; |
05 | import com.javacodegeeks.snippets.enterprise.Employee; |
07 | public interface JDBCEmployeeDAO { |
09 | public void insert(Employee employee); |
10 | public Employee findById( int id); |
11 | public List<Employee> findAll(); |
12 | public String findNameById( int id); |
JDBCEmployeeDAOImpl.java 01 | package com.javacodegeeks.snippets.enterprise.dao.impl; |
03 | import java.util.ArrayList; |
07 | import javax.sql.DataSource; |
09 | import org.springframework.jdbc.core.BeanPropertyRowMapper; |
10 | import org.springframework.jdbc.core.JdbcTemplate; |
12 | import com.javacodegeeks.snippets.enterprise.Employee; |
13 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
15 | public class JDBCEmployeeDAOImpl implements JDBCEmployeeDAO{ |
16 | private DataSource dataSource; |
17 | private JdbcTemplate jdbcTemplate; |
19 | public void setDataSource(DataSource dataSource) { |
20 | this .dataSource = dataSource; |
23 | public void insert(Employee employee){ |
25 | String sql = "INSERT INTO EMPLOYEE " + |
26 | "(ID, NAME, AGE) VALUES (?, ?, ?)" ; |
28 | jdbcTemplate = new JdbcTemplate(dataSource); |
30 | jdbcTemplate.update(sql, new Object[] { employee.getId(), |
31 | employee.getName(), employee.getAge() |
35 | @SuppressWarnings ({ "unchecked" , "rawtypes" }) |
36 | public Employee findById( int id){ |
38 | String sql = "SELECT * FROM EMPLOYEE WHERE ID = ?" ; |
40 | jdbcTemplate = new JdbcTemplate(dataSource); |
41 | Employee employee = (Employee) jdbcTemplate.queryForObject( |
42 | sql, new Object[] { id }, new BeanPropertyRowMapper(Employee. class )); |
47 | @SuppressWarnings ( "rawtypes" ) |
48 | public List<Employee> findAll(){ |
50 | jdbcTemplate = new JdbcTemplate(dataSource); |
51 | String sql = "SELECT * FROM EMPLOYEE" ; |
53 | List<Employee> employees = new ArrayList<Employee>(); |
55 | List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); |
56 | for (Map row : rows) { |
57 | Employee employee = new Employee(); |
58 | employee.setId(Integer.parseInt(String.valueOf(row.get( "ID" )))); |
59 | employee.setName((String)row.get( "NAME" )); |
60 | employee.setAge(Integer.parseInt(String.valueOf(row.get( "AGE" )))); |
61 | employees.add(employee); |
67 | public String findNameById( int id){ |
69 | String sql = "SELECT NAME FROM EMPLOYEE WHERE ID = ?" ; |
71 | String name = (String)jdbcTemplate.queryForObject( |
72 | sql, new Object[] { id }, String. class ); |
We use the new queries in App.class as shown below: App.java 01 | package com.javacodegeeks.snippets.enterprise; |
05 | import org.springframework.context.ConfigurableApplicationContext; |
06 | import org.springframework.context.support.ClassPathXmlApplicationContext; |
08 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
12 | public static void main(String[] args) { |
14 | ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml" ); |
16 | JDBCEmployeeDAO jdbcEmployeeDAO = (JDBCEmployeeDAO) context.getBean( "jdbcEmployeeDAO" ); |
18 | List<Employee> employees = jdbcEmployeeDAO.findAll(); |
19 | System.out.println(employees); |
21 | String name = jdbcEmployeeDAO.findNameById( 456 ); |
22 | System.out.println(name); |
In the result below we first see the list of Employees from the findAll() method and then the value of the name column from the findNameById(int id) method. Output [Employee [id=123, name=javacodegeeks, age=30], Employee [id=456, name=javacodegeeks, age=34]]
javacodegeeks
5.2 BatchUpdate exampleThe batchUpdate() method of JdbcTemplate class can be used to perform all batch inserts to the database. Below there are two implementations of a batchUpdate() to the database. The first one, insertBatch1(final List<Employee> employees) uses the BatchPreparedStatementSetter to insert a list of Objects to the database. The BatchPreparedStatementSetter is passed as the second parameter in the batchUpdate() method. It provides two methods that can be overriden. The getBatchSize() method provides the size of the current batch, whereas the setValues(PreparedStatement ps, int i) method is used to set the values for the parameters of the prepared statement. The second method insertBatch2(final String sql) calls the batchUpdate() method of JDBCTemplate class to execute an sql statement. JDBCEmployeeDAO.java 01 | package com.javacodegeeks.snippets.enterprise.dao; |
05 | import com.javacodegeeks.snippets.enterprise.Employee; |
07 | public interface JDBCEmployeeDAO { |
09 | public void insert(Employee employee); |
10 | public Employee findById( int id); |
11 | public List<Employee> findAll(); |
12 | public String findNameById( int id); |
13 | public void insertBatch1( final List<Employee> employees); |
14 | public void insertBatch2( final String sql); |
JDBCEmployeeDAO.java 001 | package com.javacodegeeks.snippets.enterprise.dao.impl; |
003 | import java.sql.PreparedStatement; |
004 | import java.sql.SQLException; |
005 | import java.util.ArrayList; |
006 | import java.util.List; |
009 | import javax.sql.DataSource; |
011 | import org.springframework.jdbc.core.BatchPreparedStatementSetter; |
012 | import org.springframework.jdbc.core.BeanPropertyRowMapper; |
013 | import org.springframework.jdbc.core.JdbcTemplate; |
015 | import com.javacodegeeks.snippets.enterprise.Employee; |
016 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
018 | public class JDBCEmployeeDAOImpl implements JDBCEmployeeDAO{ |
019 | private DataSource dataSource; |
020 | private JdbcTemplate jdbcTemplate; |
022 | public void setDataSource(DataSource dataSource) { |
023 | this .dataSource = dataSource; |
026 | public void insert(Employee employee){ |
028 | String sql = "INSERT INTO EMPLOYEE " + |
029 | "(ID, NAME, AGE) VALUES (?, ?, ?)" ; |
031 | jdbcTemplate = new JdbcTemplate(dataSource); |
033 | jdbcTemplate.update(sql, new Object[] { employee.getId(), |
034 | employee.getName(), employee.getAge() |
038 | @SuppressWarnings ({ "unchecked" , "rawtypes" }) |
039 | public Employee findById( int id){ |
041 | String sql = "SELECT * FROM EMPLOYEE WHERE ID = ?" ; |
043 | jdbcTemplate = new JdbcTemplate(dataSource); |
044 | Employee employee = (Employee) jdbcTemplate.queryForObject( |
045 | sql, new Object[] { id }, new BeanPropertyRowMapper(Employee. class )); |
050 | @SuppressWarnings ( "rawtypes" ) |
051 | public List<Employee> findAll(){ |
053 | jdbcTemplate = new JdbcTemplate(dataSource); |
054 | String sql = "SELECT * FROM EMPLOYEE" ; |
056 | List<Employee> employees = new ArrayList<Employee>(); |
058 | List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); |
059 | for (Map row : rows) { |
060 | Employee employee = new Employee(); |
061 | employee.setId(Integer.parseInt(String.valueOf(row.get( "ID" )))); |
062 | employee.setName((String)row.get( "NAME" )); |
063 | employee.setAge(Integer.parseInt(String.valueOf(row.get( "AGE" )))); |
064 | employees.add(employee); |
070 | public String findNameById( int id){ |
072 | jdbcTemplate = new JdbcTemplate(dataSource); |
073 | String sql = "SELECT NAME FROM EMPLOYEE WHERE ID = ?" ; |
075 | String name = (String)jdbcTemplate.queryForObject( |
076 | sql, new Object[] { id }, String. class ); |
081 | public void insertBatchSQL( final String sql){ |
083 | jdbcTemplate.batchUpdate( new String[]{sql}); |
087 | public void insertBatch1( final List<Employee> employees){ |
089 | jdbcTemplate = new JdbcTemplate(dataSource); |
090 | String sql = "INSERT INTO EMPLOYEE " + |
091 | "(ID, NAME, AGE) VALUES (?, ?, ?)" ; |
093 | jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() { |
095 | public void setValues(PreparedStatement ps, int i) throws SQLException { |
096 | Employee employee = employees.get(i); |
097 | ps.setLong( 1 , employee.getId()); |
098 | ps.setString( 2 , employee.getName()); |
099 | ps.setInt( 3 , employee.getAge() ); |
102 | public int getBatchSize() { |
103 | return employees.size(); |
108 | public void insertBatch2( final String sql){ |
109 | jdbcTemplate = new JdbcTemplate(dataSource); |
110 | jdbcTemplate.batchUpdate( new String[]{sql}); |
Let’s run App.java class again. We call the two new methods to insert two new rows to the Employee table and then update the table setting all values of a a column to a specified value. App.java 01 | package com.javacodegeeks.snippets.enterprise; |
03 | import java.util.ArrayList; |
06 | import org.springframework.context.ConfigurableApplicationContext; |
07 | import org.springframework.context.support.ClassPathXmlApplicationContext; |
08 | import org.springframework.jdbc.core.JdbcTemplate; |
10 | import com.javacodegeeks.snippets.enterprise.dao.JDBCEmployeeDAO; |
14 | public static void main(String[] args) { |
16 | ConfigurableApplicationContext context = new ClassPathXmlApplicationContext( "applicationContext.xml" ); |
18 | JDBCEmployeeDAO jdbcEmployeeDAO = (JDBCEmployeeDAO) context.getBean( "jdbcEmployeeDAO" ); |
20 | Employee emplNew1 = new Employee( 23 , "John" , 23 ); |
21 | Employee emplNew2 = new Employee( 223 , "Mark" , 43 ); |
22 | List<Employee> employeesN = new ArrayList(); |
23 | employeesN.add(emplNew1); |
24 | employeesN.add(emplNew2); |
25 | jdbcEmployeeDAO.insertBatch1(employeesN); |
26 | System.out.println( " inserted rows: " + employeesN); |
28 | System.out.println( " FindAll : " + jdbcEmployeeDAO.findAll()); |
29 | jdbcEmployeeDAO.insertBatch2( "UPDATE EMPLOYEE SET NAME ='Mary'" ); |
31 | List<Employee> employees = jdbcEmployeeDAO.findAll(); |
32 | System.out.println( "Updated column name of table: " + employees); |
34 | System.out.println( " FindAll : " + jdbcEmployeeDAO.findAll()); |
The result is shown below: Output inserted rows: [Employee [id=23, name=John, age=23], Employee [id=223, name=Mark, age=43]]
FindAll : [Employee [id=23, name=John, age=23], Employee [id=223, name=Mark, age=43]]
Updated column name of table: [Employee [id=23, name=Mary, age=23], Employee [id=223, name=Mary, age=43]]
FindAll : [Employee [id=23, name=Mary, age=23], Employee [id=223, name=Mary, age=43]]
|