Skip to content

Commit 91e3dd5

Browse files
BAEL-4350: Difference between Statement and PreparedStatement
Signed-off-by: Ali Ben Messaoud <[email protected]>
1 parent c6eba53 commit 91e3dd5

File tree

8 files changed

+441
-0
lines changed

8 files changed

+441
-0
lines changed

persistence-modules/core-java-persistence/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@
1010
- [Guide to the JDBC ResultSet Interface](https://www.baeldung.com/jdbc-resultset)
1111
- [Types of SQL Joins](https://www.baeldung.com/sql-joins)
1212
- [Returning the Generated Keys in JDBC](https://www.baeldung.com/jdbc-returning-generated-keys)
13+
- [Difference between Statement and PreparedStatement](https://www.baeldung.com/difference-between-statement-and-preparedstatement)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package com.baeldung.statmentVsPreparedstatment;
2+
3+
import java.sql.Connection;
4+
import java.sql.DriverManager;
5+
import java.sql.SQLException;
6+
7+
public class DatasourceFactory {
8+
9+
private Connection connection;
10+
11+
public Connection getConnection() throws ClassNotFoundException, SQLException {
12+
Class.forName("org.h2.Driver");
13+
connection = DriverManager.getConnection("jdbc:h2:mem:db_basic", "SA", "");
14+
connection.setAutoCommit(false);
15+
return connection;
16+
}
17+
18+
public boolean createTables() throws SQLException {
19+
String query = "create table if not exists PERSONS (ID INT, NAME VARCHAR(45))";
20+
return connection.createStatement().executeUpdate(query) == 0;
21+
}
22+
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package com.baeldung.statmentVsPreparedstatment;
2+
3+
import java.util.Objects;
4+
5+
public class PersonEntity {
6+
private int id;
7+
private String name;
8+
9+
public PersonEntity(int id, String name) {
10+
this.id = id;
11+
this.name = name;
12+
}
13+
14+
public int getId() {
15+
return id;
16+
}
17+
18+
public void setId(int id) {
19+
this.id = id;
20+
}
21+
22+
public String getName() {
23+
return name;
24+
}
25+
26+
public void setName(String name) {
27+
this.name = name;
28+
}
29+
30+
@Override public boolean equals(Object o) {
31+
if (this == o)
32+
return true;
33+
if (o == null || getClass() != o.getClass())
34+
return false;
35+
PersonEntity that = (PersonEntity) o;
36+
return id == that.id && Objects.equals(name, that.name);
37+
}
38+
39+
@Override public int hashCode() {
40+
return Objects.hash(id, name);
41+
}
42+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package com.baeldung.statmentVsPreparedstatment;
2+
3+
import java.sql.Connection;
4+
import java.sql.PreparedStatement;
5+
import java.sql.ResultSet;
6+
import java.sql.SQLException;
7+
import java.util.ArrayList;
8+
import java.util.List;
9+
import java.util.Optional;
10+
11+
public class PreparedStatementPersonDao {
12+
13+
private final Connection connection;
14+
15+
public PreparedStatementPersonDao(Connection connection) {
16+
this.connection = connection;
17+
}
18+
19+
public Optional<PersonEntity> getById(int id) throws SQLException {
20+
String query = "SELECT id, name FROM persons WHERE id = ?";
21+
22+
PreparedStatement preparedStatement = connection.prepareStatement(query);
23+
preparedStatement.setInt(1, id);
24+
ResultSet resultSet = preparedStatement.executeQuery();
25+
26+
if (resultSet.first()) {
27+
28+
PersonEntity result = new PersonEntity(resultSet.getInt("id"),
29+
resultSet.getString("name"));
30+
31+
return Optional.of(result);
32+
} else {
33+
return Optional.empty();
34+
}
35+
36+
}
37+
38+
public void insert(PersonEntity personEntity) throws SQLException {
39+
40+
String query = "INSERT INTO persons(id, name) VALUES( ?, ?)";
41+
42+
PreparedStatement preparedStatement = connection.prepareStatement(query);
43+
preparedStatement.setInt(1, personEntity.getId());
44+
preparedStatement.setString(2, personEntity.getName());
45+
preparedStatement.executeUpdate();
46+
47+
}
48+
49+
public void insert(List<PersonEntity> personEntities) throws SQLException {
50+
String query = "INSERT INTO persons(id, name) VALUES( ?, ?)";
51+
52+
PreparedStatement preparedStatement = connection.prepareStatement(query);
53+
for (PersonEntity personEntity : personEntities) {
54+
preparedStatement.setInt(1, personEntity.getId());
55+
preparedStatement.setString(2, personEntity.getName());
56+
preparedStatement.addBatch();
57+
}
58+
preparedStatement.executeBatch();
59+
60+
}
61+
62+
public void update(PersonEntity personEntity) throws SQLException {
63+
String query = "UPDATE persons SET name = ? WHERE id = ?";
64+
PreparedStatement preparedStatement = connection.prepareStatement(query);
65+
preparedStatement.setString(1, personEntity.getName());
66+
preparedStatement.setInt(2, personEntity.getId());
67+
preparedStatement.executeUpdate();
68+
}
69+
70+
public void deleteById(int id) throws SQLException {
71+
String query = "DELETE FROM persons WHERE id = ?";
72+
PreparedStatement preparedStatement = connection.prepareStatement(query);
73+
preparedStatement.setInt(1, id);
74+
preparedStatement.executeUpdate();
75+
}
76+
77+
public List<PersonEntity> getAll() throws SQLException {
78+
String query = "SELECT id, name FROM persons";
79+
80+
PreparedStatement preparedStatement = connection.prepareStatement(query);
81+
ResultSet resultSet = preparedStatement.executeQuery();
82+
List<PersonEntity> result = new ArrayList<>();
83+
while (resultSet.next()) {
84+
result.add(new PersonEntity(resultSet.getInt("id"), resultSet.getString("name")));
85+
}
86+
return result;
87+
}
88+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
package com.baeldung.statmentVsPreparedstatment;
2+
3+
import java.sql.Connection;
4+
import java.sql.ResultSet;
5+
import java.sql.SQLException;
6+
import java.sql.Statement;
7+
import java.util.ArrayList;
8+
import java.util.List;
9+
import java.util.Optional;
10+
11+
public class StatementPersonDao {
12+
13+
private final Connection connection;
14+
15+
public StatementPersonDao(Connection connection) {
16+
this.connection = connection;
17+
}
18+
19+
public Optional<PersonEntity> getById(int id) throws SQLException {
20+
String query = "SELECT id, name, FROM persons WHERE id = '" + id + "'";
21+
22+
Statement statement = connection.createStatement();
23+
ResultSet resultSet = statement.executeQuery(query);
24+
25+
if (resultSet.first()) {
26+
PersonEntity result = new PersonEntity(resultSet.getInt("id"),
27+
resultSet.getString("name"));
28+
return Optional.of(result);
29+
} else {
30+
return Optional.empty();
31+
}
32+
}
33+
34+
public void insert(PersonEntity personEntity) throws SQLException {
35+
String query = "INSERT INTO persons(id, name) VALUES(" + personEntity.getId() + ", '"
36+
+ personEntity.getName() + "')";
37+
38+
Statement statement = connection.createStatement();
39+
statement.executeUpdate(query);
40+
}
41+
42+
public void insert(List<PersonEntity> personEntities) throws SQLException {
43+
for (PersonEntity personEntity : personEntities) {
44+
insert(personEntity);
45+
}
46+
}
47+
48+
public void update(PersonEntity personEntity) throws SQLException {
49+
50+
String query = "UPDATE persons SET name = '" + personEntity.getName() + "' WHERE id = "
51+
+ personEntity.getId();
52+
53+
Statement statement = connection.createStatement();
54+
statement.executeUpdate(query);
55+
56+
}
57+
58+
public void deleteById(int id) throws SQLException {
59+
String query = "DELETE FROM persons WHERE id = " + id;
60+
Statement statement = connection.createStatement();
61+
statement.executeUpdate(query);
62+
}
63+
64+
public List<PersonEntity> getAll() throws SQLException {
65+
String query = "SELECT id, name, FROM persons";
66+
67+
Statement statement = connection.createStatement();
68+
ResultSet resultSet = statement.executeQuery(query);
69+
List<PersonEntity> result = new ArrayList<>();
70+
while (resultSet.next()) {
71+
result.add(new PersonEntity(resultSet.getInt("id"), resultSet.getString("name")));
72+
}
73+
return result;
74+
}
75+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package com.baeldung.statmentVsPreparedstatment;
2+
3+
import org.junit.jupiter.api.Test;
4+
5+
import java.sql.Connection;
6+
import java.sql.SQLException;
7+
8+
import static org.junit.jupiter.api.Assertions.assertFalse;
9+
import static org.junit.jupiter.api.Assertions.assertTrue;
10+
11+
class DatasourceFactoryUnitTest {
12+
13+
@Test
14+
void whenCreateConnectionAndTables_thenConnectionIsOpenAndTableIsCreated()
15+
throws SQLException, ClassNotFoundException {
16+
DatasourceFactory factory = new DatasourceFactory();
17+
Connection connection = factory.getConnection();
18+
19+
assertFalse(connection.isClosed());
20+
assertTrue(factory.createTables());
21+
}
22+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package com.baeldung.statmentVsPreparedstatment;
2+
3+
import org.junit.jupiter.api.BeforeEach;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.sql.Connection;
7+
import java.sql.SQLException;
8+
import java.util.Arrays;
9+
import java.util.List;
10+
import java.util.Optional;
11+
12+
import static org.junit.jupiter.api.Assertions.*;
13+
14+
class PreparedStatementPersonDaoUnitTest {
15+
private PreparedStatementPersonDao dao;
16+
17+
@BeforeEach
18+
void setup() throws SQLException, ClassNotFoundException {
19+
DatasourceFactory datasourceFactory = new DatasourceFactory();
20+
Connection connection = datasourceFactory.getConnection();
21+
datasourceFactory.createTables();
22+
dao = new PreparedStatementPersonDao(connection);
23+
}
24+
25+
@Test
26+
void whenInsertAPerson_thenItNeverThrowsAnException() {
27+
assertDoesNotThrow(() -> dao.insert(new PersonEntity(1, "john")));
28+
}
29+
30+
@Test
31+
void whenInsertAPersonWithQuoteInText_thenItNeverThrowsAnException() {
32+
assertDoesNotThrow(() -> dao.insert(new PersonEntity(1, "O'Brien")));
33+
}
34+
35+
@Test
36+
void whenGetAPersonById_thenItReturnThePersonInDatabase() throws SQLException {
37+
dao.insert(new PersonEntity(1, "john"));
38+
39+
Optional<PersonEntity> maybeEmployee = dao.getById(1);
40+
assertTrue(maybeEmployee.isPresent());
41+
42+
PersonEntity personEntity = maybeEmployee.get();
43+
44+
assertEquals(1, personEntity.getId());
45+
assertEquals("john", personEntity.getName());
46+
}
47+
48+
@Test
49+
void whenInsertAndGetMultiplePersons_thenItNeverThrowsAnException() throws SQLException {
50+
assertDoesNotThrow(() -> dao.insert(
51+
Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skit"))));
52+
53+
List<PersonEntity> result = dao.getAll();
54+
55+
assertEquals(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skit")),
56+
result);
57+
}
58+
59+
@Test
60+
void whenUpdateAnExistentPerson_thenItReturnsTheUpdatedPerson() throws SQLException {
61+
dao.insert(new PersonEntity(1, "john"));
62+
dao.update(new PersonEntity(1, "johnny"));
63+
64+
Optional<PersonEntity> maybePerson = dao.getById(1);
65+
66+
assertTrue(maybePerson.isPresent());
67+
68+
PersonEntity personEntity = maybePerson.get();
69+
70+
assertEquals(1, personEntity.getId());
71+
assertEquals("johnny", personEntity.getName());
72+
}
73+
74+
@Test
75+
void whenDeleteAPersonById_thenItWillBeAbsentInDatabase() throws SQLException {
76+
dao.insert(new PersonEntity(1, "john"));
77+
dao.deleteById(1);
78+
79+
Optional<PersonEntity> maybePerson = dao.getById(1);
80+
81+
assertFalse(maybePerson.isPresent());
82+
}
83+
84+
@Test
85+
void whenAHackerUpdateAPerson_thenItUpdatesTheTargetPerson() throws SQLException {
86+
dao.insert(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skeet")));
87+
dao.update(new PersonEntity(1, "hacker' --"));
88+
89+
List<PersonEntity> result = dao.getAll();
90+
91+
assertEquals(Arrays.asList(new PersonEntity(1, "hacker' --"), new PersonEntity(2, "skeet")),
92+
result);
93+
}
94+
}

0 commit comments

Comments
 (0)