-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathArticleRepositoryImpl.java
More file actions
72 lines (62 loc) · 2.67 KB
/
ArticleRepositoryImpl.java
File metadata and controls
72 lines (62 loc) · 2.67 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
package db;
import model.Article;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class ArticleRepositoryImpl implements ArticleRepository {
private static final String JDBC_URL = "jdbc:h2:tcp://localhost/~/h2-db/was-be";
private static final String USER = "sa";
private static final String PASSWORD = "sa";
private static final Logger logger = LoggerFactory.getLogger(ArticleRepositoryImpl.class);
public Article save(Article article) {
String sql = "insert into article_tbl(creatorId, title, content, image_url) values(?, ?, ?, ?)";
try (
Connection con = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
PreparedStatement pstmt = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
) {
pstmt.setLong(1, article.getCreatorId());
pstmt.setString(2, article.getTitle());
pstmt.setString(3, article.getContent());
pstmt.setString(4, article.getImageUrl());
pstmt.executeUpdate();
try (ResultSet rs = pstmt.getGeneratedKeys()) {
if (!rs.next()) {
throw new SQLException("조회 실패");
}
long id = rs.getLong(1);
article.setId(id);
}
return article;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
@Override
public List<Article> findTopNLessThanByIdDecreasingOrder(int limit, long id) {
String sql = "select id, creatorId, title, content, image_url from article_tbl where id < ? order by id desc limit ?";
try (
Connection con = DriverManager.getConnection(JDBC_URL, USER, PASSWORD);
PreparedStatement pstmt = con.prepareStatement(sql);
) {
List<Article> articles = new ArrayList<>();
pstmt.setLong(1, id);
pstmt.setLong(2, limit);
try (ResultSet rs = pstmt.executeQuery()) {
while(rs.next()) {
long articleId = rs.getLong("id");
long creatorId = rs.getLong("creatorId");
String title = rs.getString("title");
String content = rs.getString("content");
String imageUrl = rs.getString("image_url");
articles.add(new Article(articleId, creatorId, title, content, imageUrl));
}
}
return articles;
} catch (SQLException e) {
logger.error("DB 접속 실패", e);
throw new RuntimeException(e);
}
}
}