-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathCityRepository.java
More file actions
102 lines (85 loc) · 2.77 KB
/
CityRepository.java
File metadata and controls
102 lines (85 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package daos;
import models.City;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author git-leon
* @version 1.0.0
* @date 8/4/21 3:05 PM
*/
public class CityRepository implements Repo {
private Connection connection;
public CityRepository(Connection connection) {
this.connection = connection;
}
@Override
public Connection getConnection() {
return connection;
}
public void create(City city) {
executeStatement(String.format(new StringBuilder()
.append("INSERT INTO ciudades.city(")
.append("id, name, population, level) ")
.append("VALUES (%s, '%s', %s, %s);")
.toString(),
city.getId(),
city.getName(),
city.getPopulation(),
city.getLevel()));
}
public List<City> readAll() {
ResultSet resultSet = executeQuery("SELECT * FROM ciudades.city;");
List<City> list = new ArrayList<>();
try {
while (resultSet.next()) {
String id = resultSet.getString(1);
String name = resultSet.getString(2);
Integer population = resultSet.getInt(3);
Integer level = resultSet.getInt(4);
list.add(new City(
Long.parseLong(id),
name,
population,
level));
// Integer.parseInt(population),
// Integer.parseInt(level)));
}
} catch (SQLException throwables) {
throw new RuntimeException(throwables);
}
return list;
}
public City read(Long cityId) {
return readAll()
.stream()
.filter(City -> City.getId().equals(cityId))
.findAny()
.get();
}
public void update(Long id, City newCityData) {
executeStatement(String.format(new StringBuilder()
.append("UPDATE ciudades.city SET ")
.append("name = '%s', ")
.append("population = '%s',")
.append("level = '%s' ")
.append("WHERE id = %s;")
.toString(),
newCityData.getName(),
newCityData.getPopulation(),
newCityData.getLevel(),
id));
}
public void delete(Long id) {
executeStatement(String.format(new StringBuilder()
.append("DELETE FROM ciudades.city ")
.append("WHERE id = %s;")
.toString(),
id));
}
public void delete(City city) {
delete(city.getId());
}
}