Skip to content

Commit d76aaf0

Browse files
authoredJul 17, 2020
Merge pull request eugenp#9645 from alibenmessaoud/BAEL-4350
BAEL-4350: Difference between Statement and PreparedStatement
2 parents 8d1c5ab + aaafccc commit d76aaf0

File tree

7 files changed

+440
-0
lines changed

7 files changed

+440
-0
lines changed
 
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+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
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 StatementPersonDaoUnitTest {
15+
16+
private StatementPersonDao dao;
17+
18+
@BeforeEach
19+
void setup() throws SQLException, ClassNotFoundException {
20+
DatasourceFactory datasourceFactory = new DatasourceFactory();
21+
Connection connection = datasourceFactory.getConnection();
22+
datasourceFactory.createTables();
23+
dao = new StatementPersonDao(connection);
24+
}
25+
26+
@Test
27+
void whenInsertAPerson_thenItNeverThrowsAnException() {
28+
assertDoesNotThrow(() -> dao.insert(new PersonEntity(1, "john")));
29+
}
30+
31+
@Test
32+
void whenInsertAPersonWithQuoteInText_thenItWillThrowAnException() {
33+
assertThrows(SQLException.class, () -> dao.insert(new PersonEntity(1, "O'Brien")));
34+
}
35+
36+
@Test
37+
void whenGetAPersonById_thenItReturnThePersonInDatabase() throws SQLException {
38+
dao.insert(new PersonEntity(1, "john"));
39+
40+
Optional<PersonEntity> maybeEmployee = dao.getById(1);
41+
42+
assertTrue(maybeEmployee.isPresent());
43+
44+
PersonEntity personEntity = maybeEmployee.get();
45+
46+
assertEquals(1, personEntity.getId());
47+
assertEquals("john", personEntity.getName());
48+
}
49+
50+
@Test
51+
void whenInsertAndGetMultiplePersons_thenItNeverThrowsAnException() throws SQLException {
52+
assertDoesNotThrow(() -> dao.insert(
53+
Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skeet"))));
54+
55+
List<PersonEntity> result = dao.getAll();
56+
57+
assertEquals(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skeet")),
58+
result);
59+
}
60+
61+
@Test
62+
void whenUpdateAnExistentPerson_thenItReturnsTheUpdatedPerson() throws SQLException {
63+
dao.insert(new PersonEntity(1, "john"));
64+
dao.update(new PersonEntity(1, "johnny"));
65+
66+
Optional<PersonEntity> maybePerson = dao.getById(1);
67+
68+
assertTrue(maybePerson.isPresent());
69+
70+
PersonEntity personEntity = maybePerson.get();
71+
72+
assertEquals(1, personEntity.getId());
73+
assertEquals("johnny", personEntity.getName());
74+
}
75+
76+
@Test
77+
void whenDeleteAPersonById_thenItWillBeAbsentInDatabase() throws SQLException {
78+
dao.insert(new PersonEntity(1, "john"));
79+
dao.deleteById(1);
80+
81+
Optional<PersonEntity> maybePerson = dao.getById(1);
82+
83+
assertFalse(maybePerson.isPresent());
84+
}
85+
86+
@Test
87+
void whenAHackerUpdateAPerson_thenItAllPersonsAreUpdated() throws SQLException {
88+
dao.insert(Arrays.asList(new PersonEntity(1, "john"), new PersonEntity(2, "skeet")));
89+
dao.update(new PersonEntity(1, "hacker' --"));
90+
91+
List<PersonEntity> result = dao.getAll();
92+
93+
assertEquals(Arrays.asList(new PersonEntity(1, "hacker"), new PersonEntity(2, "hacker")),
94+
result);
95+
}
96+
}

0 commit comments

Comments
 (0)
Please sign in to comment.