Skip to content

Commit 5bfbea1

Browse files
author
Eugen
committed
Merge pull request eugenp#117 from mgooty/master
Sample code for Spring JDBC examples.
2 parents 9e1ae6d + 17d3934 commit 5bfbea1

File tree

10 files changed

+438
-1
lines changed

10 files changed

+438
-1
lines changed

spring-all/pom.xml

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,11 @@
5050
<version>${mysql-connector-java.version}</version>
5151
<scope>runtime</scope>
5252
</dependency>
53-
53+
<dependency>
54+
<groupId>org.hsqldb</groupId>
55+
<artifactId>hsqldb</artifactId>
56+
<version>2.3.2</version>
57+
</dependency>
5458
<!-- validation -->
5559

5660
<dependency>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package org.baeldung.jdbc;
2+
3+
import java.sql.SQLException;
4+
5+
import org.springframework.dao.DataAccessException;
6+
import org.springframework.dao.DuplicateKeyException;
7+
import org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator;
8+
9+
public class CustomSQLErrorCodeTranslator extends
10+
SQLErrorCodeSQLExceptionTranslator {
11+
12+
@Override
13+
protected DataAccessException customTranslate(final String task,
14+
final String sql, final SQLException sqlException) {
15+
if (sqlException.getErrorCode() == -104) {
16+
return new DuplicateKeyException(
17+
"Custome Exception translator - Integrity contraint voilation.",
18+
sqlException);
19+
}
20+
return null;
21+
}
22+
23+
}
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package org.baeldung.jdbc;
2+
3+
public class Employee {
4+
private int id;
5+
6+
private String firstName;
7+
8+
private String lastName;
9+
10+
private String address;
11+
12+
public int getId() {
13+
return id;
14+
}
15+
16+
public void setId(final int id) {
17+
this.id = id;
18+
}
19+
20+
public String getFirstName() {
21+
return firstName;
22+
}
23+
24+
public void setFirstName(final String firstName) {
25+
this.firstName = firstName;
26+
}
27+
28+
public String getLastName() {
29+
return lastName;
30+
}
31+
32+
public void setLastName(final String lastName) {
33+
this.lastName = lastName;
34+
}
35+
36+
public String getAddress() {
37+
return address;
38+
}
39+
40+
public void setAddress(final String address) {
41+
this.address = address;
42+
}
43+
44+
}
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
package org.baeldung.jdbc;
2+
3+
import java.sql.PreparedStatement;
4+
import java.sql.SQLException;
5+
import java.util.HashMap;
6+
import java.util.List;
7+
import java.util.Map;
8+
9+
import javax.sql.DataSource;
10+
11+
import org.springframework.beans.factory.annotation.Autowired;
12+
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
13+
import org.springframework.jdbc.core.JdbcTemplate;
14+
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
15+
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
16+
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
17+
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
18+
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
19+
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
20+
import org.springframework.stereotype.Repository;
21+
22+
@Repository
23+
public class EmployeeDAO {
24+
25+
private JdbcTemplate jdbcTemplate;
26+
27+
private NamedParameterJdbcTemplate namedParameterJdbcTemplate;
28+
29+
private SimpleJdbcInsert simpleJdbcInsert;
30+
31+
@Autowired
32+
public void setDataSource(final DataSource dataSource) {
33+
jdbcTemplate = new JdbcTemplate(dataSource);
34+
final CustomSQLErrorCodeTranslator customSQLErrorCodeTranslator = new CustomSQLErrorCodeTranslator();
35+
jdbcTemplate.setExceptionTranslator(customSQLErrorCodeTranslator);
36+
37+
namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
38+
simpleJdbcInsert = new SimpleJdbcInsert(dataSource)
39+
.withTableName("EMPLOYEE");
40+
41+
}
42+
43+
public int getCountOfEmployees() {
44+
return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM EMPLOYEE",
45+
Integer.class);
46+
}
47+
48+
public List<Employee> getAllEmployees() {
49+
return jdbcTemplate.query("SELECT * FROM EMPLOYEE",
50+
new EmployeeRowMapper());
51+
}
52+
53+
public int addEmplyee(final int id) {
54+
return jdbcTemplate.update("INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)",
55+
id, "Bill", "Gates", "USA");
56+
}
57+
58+
public int addEmplyeeUsingSimpelJdbcInsert(final Employee emp) {
59+
final Map<String, Object> parameters = new HashMap<String, Object>();
60+
parameters.put("ID", emp.getId());
61+
parameters.put("FIRST_NAME", emp.getFirstName());
62+
parameters.put("LAST_NAME", emp.getLastName());
63+
parameters.put("ADDRESS", emp.getAddress());
64+
65+
return simpleJdbcInsert.execute(parameters);
66+
}
67+
68+
public Employee getEmployee(final int id) {
69+
final String query = "SELECT * FROM EMPLOYEE WHERE ID = ?";
70+
return jdbcTemplate.queryForObject(query, new Object[] { id },
71+
new EmployeeRowMapper());
72+
}
73+
74+
public void addEmplyeeUsingExecuteMethod() {
75+
jdbcTemplate
76+
.execute("INSERT INTO EMPLOYEE VALUES (6, 'Bill', 'Gates', 'USA')");
77+
}
78+
79+
public String getEmployeeUsingMapSqlParameterSource() {
80+
final SqlParameterSource namedParameters = new MapSqlParameterSource()
81+
.addValue("id", 1);
82+
83+
return namedParameterJdbcTemplate.queryForObject(
84+
"SELECT FIRST_NAME FROM EMPLOYEE WHERE ID = :id",
85+
namedParameters, String.class);
86+
}
87+
88+
public int getEmployeeUsingBeanPropertySqlParameterSource() {
89+
final Employee employee = new Employee();
90+
employee.setFirstName("James");
91+
92+
final String SELECT_BY_ID = "SELECT COUNT(*) FROM EMPLOYEE WHERE FIRST_NAME = :firstName";
93+
94+
final SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(
95+
employee);
96+
97+
return namedParameterJdbcTemplate.queryForObject(SELECT_BY_ID,
98+
namedParameters, Integer.class);
99+
}
100+
101+
public int[] batchUpdateUsingJDBCTemplate(final List<Employee> employees) {
102+
return jdbcTemplate.batchUpdate(
103+
"INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)",
104+
new BatchPreparedStatementSetter() {
105+
106+
@Override
107+
public void setValues(final PreparedStatement ps,
108+
final int i) throws SQLException {
109+
ps.setInt(1, employees.get(i).getId());
110+
ps.setString(2, employees.get(i).getFirstName());
111+
ps.setString(3, employees.get(i).getLastName());
112+
ps.setString(4, employees.get(i).getAddress());
113+
}
114+
115+
@Override
116+
public int getBatchSize() {
117+
return 3;
118+
}
119+
});
120+
}
121+
122+
public int[] batchUpdateUsingNamedParameterJDBCTemplate(
123+
final List<Employee> employees) {
124+
final SqlParameterSource[] batch = SqlParameterSourceUtils
125+
.createBatch(employees.toArray());
126+
final int[] updateCounts = namedParameterJdbcTemplate
127+
.batchUpdate(
128+
"INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)",
129+
batch);
130+
return updateCounts;
131+
}
132+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package org.baeldung.jdbc;
2+
3+
import java.sql.ResultSet;
4+
import java.sql.SQLException;
5+
6+
import org.springframework.jdbc.core.RowMapper;
7+
8+
public class EmployeeRowMapper implements RowMapper<Employee> {
9+
10+
@Override
11+
public Employee mapRow(final ResultSet rs, final int rowNum)
12+
throws SQLException {
13+
final Employee employee = new Employee();
14+
15+
employee.setId(rs.getInt("ID"));
16+
employee.setFirstName(rs.getString("FIRST_NAME"));
17+
employee.setLastName(rs.getString("LAST_NAME"));
18+
employee.setAddress(rs.getString("ADDRESS"));
19+
20+
return employee;
21+
}
22+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package org.baeldung.jdbc.config;
2+
3+
import javax.sql.DataSource;
4+
5+
import org.springframework.context.annotation.Bean;
6+
import org.springframework.context.annotation.ComponentScan;
7+
import org.springframework.context.annotation.Configuration;
8+
import org.springframework.jdbc.datasource.DriverManagerDataSource;
9+
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
10+
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
11+
12+
@Configuration
13+
@ComponentScan("org.baeldung.jdbc")
14+
public class SpringJdbcConfig {
15+
16+
@Bean
17+
public DataSource dataSource() {
18+
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
19+
.addScript("classpath:jdbc/schema.sql")
20+
.addScript("classpath:jdbc/test-data.sql").build();
21+
}
22+
23+
// @Bean
24+
public DataSource mysqlDataSource() {
25+
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
26+
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
27+
dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");
28+
dataSource.setUsername("guest_user");
29+
dataSource.setPassword("guest_password");
30+
31+
return dataSource;
32+
}
33+
34+
}
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
CREATE TABLE EMPLOYEE
2+
(
3+
ID int NOT NULL PRIMARY KEY,
4+
FIRST_NAME varchar(255),
5+
LAST_NAME varchar(255),
6+
ADDRESS varchar(255),
7+
);
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<beans xmlns="http://www.springframework.org/schema/beans"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
4+
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
5+
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">
6+
7+
<bean id="employeeDao" class="org.baeldung.jdbc.EmployeeDAO">
8+
<property name="dataSource" ref="dataSource" />
9+
</bean>
10+
11+
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
12+
destroy-method="close">
13+
<property name="driverClassName" value="${jdbc.driverClassName}" />
14+
<property name="url" value="${jdbc.url}" />
15+
<property name="username" value="${jdbc.username}" />
16+
<property name="password" value="${jdbc.password}" />
17+
</bean>
18+
19+
<context:property-placeholder location="jdbc.properties" />
20+
</beans>
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
INSERT INTO EMPLOYEE VALUES (1, 'James', 'Gosling', 'Canada');
2+
3+
INSERT INTO EMPLOYEE VALUES (2, 'Donald', 'Knuth', 'USA');
4+
5+
INSERT INTO EMPLOYEE VALUES (3, 'Linus', 'Torvalds', 'Finland');
6+
7+
INSERT INTO EMPLOYEE VALUES (4, 'Dennis', 'Ritchie', 'USA');

0 commit comments

Comments
 (0)