forked from taywils/java_spark_tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArticlePostgresDao.java
More file actions
246 lines (204 loc) · 7.81 KB
/
ArticlePostgresDao.java
File metadata and controls
246 lines (204 loc) · 7.81 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import java.sql.*;
import java.util.ArrayList;
public class ArticlePostgresDao<T extends Article> implements ArticleDbService<T> {
// PostgreSQL connection to the database
private Connection conn;
// A raw SQL query used without parameters
private Statement stmt;
public ArticlePostgresDao() {
// The account names setup from the command line interface
String user = "postgres";
String passwd = "postgres";
String dbName = "sparkledb";
// DB connection on localhost via JDBC
String uri = "jdbc:postgresql://localhost/" + dbName;
// Standard SQL CREATE TABLE query
// The primary key is not auto incremented
String createTableQuery =
"CREATE TABLE IF NOT EXISTS article(" +
"id INT PRIMARY KEY NOT NULL," +
"title VARCHAR(64) NOT NULL," +
"content VARCHAR(512)NOT NULL," +
"summary VARCHAR(64) NOT NULL," +
"deleted BOOLEAN DEFAULT FALSE," +
"createdAt DATE NOT NULL" +
");"
;
// Create the article table within sparkledb and close resources if an exception is thrown
try {
conn = DriverManager.getConnection(uri, user, passwd);
stmt = conn.createStatement();
stmt.execute(createTableQuery);
System.out.println("Connecting to PostgreSQL database");
} catch(Exception e) {
System.out.println(e.getMessage());
try {
if(null != stmt) {
stmt.close();
}
if(null != conn) {
conn.close();
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
}
@Override
public Boolean create(T entity) {
try {
String insertQuery = "INSERT INTO article(id, title, content, summary, createdAt) VALUES(?, ?, ?, ?, ?);";
// Prepared statements allow us to avoid SQL injection attacks
PreparedStatement pstmt = conn.prepareStatement(insertQuery);
// JDBC binds every prepared statement argument to a Java Class such as Integer and or String
pstmt.setInt(1, entity.getId());
pstmt.setString(2, entity.getTitle());
pstmt.setString(3, entity.getContent());
pstmt.setString(4, entity.getSummary());
java.sql.Date sqlNow = new Date(new java.util.Date().getTime());
pstmt.setDate(5, sqlNow);
pstmt.executeUpdate();
// Unless closed prepared statement connections will linger
// Not very important for a trivial app but it will burn you in a professional large codebase
pstmt.close();
return true;
} catch (SQLException e) {
System.out.println(e.getMessage());
try {
if(null != stmt) {
stmt.close();
}
if(null != conn) {
conn.close();
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return false;
}
}
@Override
@SuppressWarnings("unchecked")
public T readOne(int id) {
try {
String selectQuery = "SELECT * FROM article where id = ?";
PreparedStatement pstmt = conn.prepareStatement(selectQuery);
pstmt.setInt(1, id);
pstmt.executeQuery();
// A ResultSet is Class which represents a table returned by a SQL query
ResultSet resultSet = pstmt.getResultSet();
if(resultSet.next()) {
Article entity = new Article(
// You must know both the column name and the type to extract the row
resultSet.getString("title"),
resultSet.getString("summary"),
resultSet.getString("content"),
resultSet.getInt("id"),
resultSet.getDate("createdat"),
resultSet.getBoolean("deleted")
);
pstmt.close();
return (T) entity;
}
} catch(Exception e) {
System.out.println(e.getMessage());
try {
if(null != stmt) {
stmt.close();
}
if(null != conn) {
conn.close();
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
return null;
}
@Override
@SuppressWarnings("unchecked") //Tells the compiler to ignore unchecked type casts
public ArrayList<T> readAll() {
// Type cast the generic T into an Article
ArrayList<Article> results = (ArrayList<Article>) new ArrayList<T>();
try {
String query = "SELECT * FROM article;";
stmt.execute(query);
ResultSet resultSet = stmt.getResultSet();
while(resultSet.next()) {
Article entity = new Article(
resultSet.getString("title"),
resultSet.getString("summary"),
resultSet.getString("content"),
resultSet.getInt("id"),
resultSet.getDate("createdat"),
resultSet.getBoolean("deleted")
);
results.add(entity);
}
} catch(Exception e) {
System.out.println(e.getMessage());
try {
if(null != stmt) {
stmt.close();
}
if(null != conn) {
conn.close();
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
// The interface ArticleDbService relies upon the generic type T so we cast it back
return (ArrayList<T>) results;
}
@Override
public Boolean update(int id, String title, String summary, String content) {
try {
String updateQuery =
"UPDATE article SET title = ?, summary = ?, content = ?" +
"WHERE id = ?;"
;
PreparedStatement pstmt = conn.prepareStatement(updateQuery);
pstmt.setString(1, title);
pstmt.setString(2, summary);
pstmt.setString(3, content);
pstmt.setInt(4, id);
pstmt.executeUpdate();
} catch(Exception e) {
System.out.println(e.getMessage());
try {
if(null != stmt) {
stmt.close();
}
if(null != conn) {
conn.close();
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
return true;
}
@Override
public Boolean delete(int id) {
try {
String deleteQuery = "DELETE FROM article WHERE id = ?";
PreparedStatement pstmt = conn.prepareStatement(deleteQuery);
pstmt.setInt(1, id);
pstmt.executeUpdate();
} catch (Exception e) {
System.out.println(e.getMessage());
try {
if(null != stmt) {
stmt.close();
}
if(null != conn) {
conn.close();
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
}
return true;
}
}