-
Notifications
You must be signed in to change notification settings - Fork 300
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[JDBC 라이브러리 구현하기 - 1, 2단계] 다니(이다은) 미션 제출합니다. #19
Merged
Merged
Changes from all commits
Commits
Show all changes
21 commits
Select commit
Hold shift + click to select a range
50a4867
docs: README.md 작성
da-nyee a3867a6
feat: UserDao 구현
da-nyee 52d5207
docs: README.md 작성
da-nyee ed67dd3
feat: 메소드 추출
da-nyee 71c981c
feat: 클래스 추출
da-nyee 6258512
feat: 템플릿 메소드 패턴 적용, 도메인 의존도 제거
da-nyee 6d36e44
feat: 클래스 추출
da-nyee 6aca3ac
feat: 템플릿 메소드 패턴 적용
da-nyee 7396b75
feat: 불필요한 mapRow() 제거
da-nyee 4dc0e53
refactor: try-with-resources 적용
da-nyee 4be7cd9
refactor: RowMapper 인터페이스에 제네릭 사용
da-nyee 4590b31
refactor: JdbcTemplate 추상 클래스 -> JdbcTemplate 클래스 변경
da-nyee 0e9b166
refactor: PreparedStatement 인터페이스에 가변인자 사용
da-nyee d239d7a
refactor: executeQuery() 삭제
da-nyee 288c88a
docs: README.md 체크
da-nyee baf90f9
chore: JaCoCo 설정 추가
da-nyee dfef639
refactor: try-with-resources 적용
da-nyee 29762e4
refactor: getUser() -> createUser() 변경
da-nyee c223394
refactor: query()에 가변인자 추가
da-nyee 4eaf143
refactor: 부생성자 사용
da-nyee 4e633f8
test: JdbcTemplate 단위 테스트 작성
da-nyee File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -124,3 +124,6 @@ gen | |
build | ||
|
||
/tomcat.8080/ | ||
|
||
### JaCoCo ### | ||
app/jacoco |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1 +1,36 @@ | ||
# jwp-dashboard-jdbc | ||
# JDBC 라이브러리 구현하기 | ||
|
||
<br/> | ||
|
||
## JDBC 라이브러리 구현하기 | ||
|
||
- 웹 서비스를 운영하려면 `데이터 영속성`이 있어야 함 | ||
- Java 진영에서는 어플리케이션의 DB 관련 처리를 위해 JDBC API 제공 | ||
|
||
<br/> | ||
|
||
- [x] `UserDao` 구현 👉 `UserDaoTest` 활용하여 진행 | ||
- [x] `JdbcTemplate` 구현 👉 중복을 제거하기 위한 라이브러리 | ||
|
||
<br/> | ||
|
||
## 리팩토링 | ||
|
||
- [x] 메소드 추출 | ||
- createQueryForInsert(), createQueryForUpdate() | ||
- setValuesForInsert(User, PreparedStatement), setValuesForUpdate(User, PreparedStatement) | ||
- [x] 클래스 추출 | ||
- `InsertJdbcTemplate`, `UpdateJdbcTemplate` | ||
- [x] 템플릿 메소드 패턴 적용 | ||
- `JdbcTemplate` (abstract) | ||
- [x] 도메인 의존도 제거 | ||
- [x] 클래스 추출 | ||
- `SelectJdbcTemplate` | ||
- [x] 템플릿 메소드 패턴 적용 | ||
- `JdbcTemplate` (abstract) | ||
- [x] 불필요한 mapRow() 제거 | ||
- `PreparedStatementSetter` (interface), `RowMapper` (interface) | ||
- [x] 라이브러리 확장 | ||
- `RowMapper` (interface)에 제네릭 사용 | ||
- `JdbcTemplate` (abstract) -> `JdbcTemplate` | ||
- `PreparedStatementSetter` (interface)에 가변인자 사용 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
19 changes: 11 additions & 8 deletions
19
app/src/main/java/com/techcourse/config/DataSourceConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,27 +1,30 @@ | ||
package com.techcourse.config; | ||
|
||
import org.h2.jdbcx.JdbcDataSource; | ||
|
||
import java.util.Objects; | ||
import javax.sql.DataSource; | ||
import org.h2.jdbcx.JdbcDataSource; | ||
|
||
public class DataSourceConfig { | ||
|
||
private static javax.sql.DataSource INSTANCE; | ||
private static DataSource instance; | ||
|
||
public static javax.sql.DataSource getInstance() { | ||
if (Objects.isNull(INSTANCE)) { | ||
INSTANCE = createJdbcDataSource(); | ||
public static DataSource getInstance() { | ||
if (Objects.isNull(instance)) { | ||
instance = createJdbcDataSource(); | ||
} | ||
return INSTANCE; | ||
return instance; | ||
} | ||
|
||
private static JdbcDataSource createJdbcDataSource() { | ||
final JdbcDataSource jdbcDataSource = new JdbcDataSource(); | ||
|
||
jdbcDataSource.setUrl("jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;"); | ||
jdbcDataSource.setUser(""); | ||
jdbcDataSource.setPassword(""); | ||
|
||
return jdbcDataSource; | ||
} | ||
|
||
private DataSourceConfig() {} | ||
private DataSourceConfig() { | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,116 +1,50 @@ | ||
package com.techcourse.dao; | ||
|
||
import com.techcourse.domain.User; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
import javax.sql.DataSource; | ||
import java.sql.Connection; | ||
import java.sql.PreparedStatement; | ||
import java.sql.ResultSet; | ||
import java.sql.SQLException; | ||
import java.util.List; | ||
import javax.sql.DataSource; | ||
import nextstep.jdbc.JdbcTemplate; | ||
|
||
public class UserDao { | ||
|
||
private static final Logger log = LoggerFactory.getLogger(UserDao.class); | ||
|
||
private final DataSource dataSource; | ||
private final JdbcTemplate jdbcTemplate; | ||
|
||
public UserDao(DataSource dataSource) { | ||
this.dataSource = dataSource; | ||
this.jdbcTemplate = new JdbcTemplate(dataSource); | ||
} | ||
|
||
public void insert(User user) { | ||
final String sql = "insert into users (account, password, email) values (?, ?, ?)"; | ||
|
||
Connection conn = null; | ||
PreparedStatement pstmt = null; | ||
try { | ||
conn = dataSource.getConnection(); | ||
pstmt = conn.prepareStatement(sql); | ||
|
||
log.debug("query : {}", sql); | ||
|
||
pstmt.setString(1, user.getAccount()); | ||
pstmt.setString(2, user.getPassword()); | ||
pstmt.setString(3, user.getEmail()); | ||
pstmt.executeUpdate(); | ||
} catch (SQLException e) { | ||
log.error(e.getMessage(), e); | ||
throw new RuntimeException(e); | ||
} finally { | ||
try { | ||
if (pstmt != null) { | ||
pstmt.close(); | ||
} | ||
} catch (SQLException ignored) {} | ||
|
||
try { | ||
if (conn != null) { | ||
conn.close(); | ||
} | ||
} catch (SQLException ignored) {} | ||
} | ||
String sql = "insert into users (account, password, email) values (?, ?, ?)"; | ||
jdbcTemplate.update(sql, user.getAccount(), user.getPassword(), user.getEmail()); | ||
} | ||
|
||
public void update(User user) { | ||
// todo | ||
String sql = "update users set password = ? where id = ?"; | ||
jdbcTemplate.update(sql, user.getPassword(), user.getId()); | ||
} | ||
|
||
public List<User> findAll() { | ||
// todo | ||
return null; | ||
String sql = "select id, account, password, email from users"; | ||
return jdbcTemplate.query(sql, this::createUser); | ||
} | ||
|
||
public User findById(Long id) { | ||
final String sql = "select id, account, password, email from users where id = ?"; | ||
|
||
Connection conn = null; | ||
PreparedStatement pstmt = null; | ||
ResultSet rs = null; | ||
try { | ||
conn = dataSource.getConnection(); | ||
pstmt = conn.prepareStatement(sql); | ||
pstmt.setLong(1, id); | ||
rs = pstmt.executeQuery(); | ||
|
||
log.debug("query : {}", sql); | ||
|
||
if (rs.next()) { | ||
return new User( | ||
rs.getLong(1), | ||
rs.getString(2), | ||
rs.getString(3), | ||
rs.getString(4)); | ||
} | ||
return null; | ||
} catch (SQLException e) { | ||
log.error(e.getMessage(), e); | ||
throw new RuntimeException(e); | ||
} finally { | ||
try { | ||
if (rs != null) { | ||
rs.close(); | ||
} | ||
} catch (SQLException ignored) {} | ||
|
||
try { | ||
if (pstmt != null) { | ||
pstmt.close(); | ||
} | ||
} catch (SQLException ignored) {} | ||
|
||
try { | ||
if (conn != null) { | ||
conn.close(); | ||
} | ||
} catch (SQLException ignored) {} | ||
} | ||
String sql = "select id, account, password, email from users where id = ?"; | ||
return jdbcTemplate.queryForObject(sql, this::createUser, id); | ||
} | ||
|
||
public User findByAccount(String account) { | ||
// todo | ||
return null; | ||
String sql = "select id, account, password, email from users where account = ?"; | ||
return jdbcTemplate.queryForObject(sql, this::createUser, account); | ||
} | ||
|
||
private User createUser(ResultSet rs) throws SQLException { | ||
return new User( | ||
rs.getLong("id"), | ||
rs.getString("account"), | ||
rs.getString("password"), | ||
rs.getString("email")); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
35 changes: 35 additions & 0 deletions
35
app/src/main/java/com/techcourse/support/jdbc/init/DatabasePopulatingUtils.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
package com.techcourse.support.jdbc.init; | ||
|
||
import java.io.File; | ||
import java.net.URL; | ||
import java.nio.file.Files; | ||
import java.sql.Connection; | ||
import java.sql.Statement; | ||
import javax.sql.DataSource; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
public class DatabasePopulatingUtils { | ||
|
||
private static final Logger LOG = LoggerFactory.getLogger(DatabasePopulatingUtils.class); | ||
|
||
private DatabasePopulatingUtils() { | ||
} | ||
|
||
public static void execute(DataSource dataSource) { | ||
try ( | ||
Connection connection = dataSource.getConnection(); | ||
Statement statement = connection.createStatement() | ||
) { | ||
final URL url = DatabasePopulatingUtils.class | ||
.getClassLoader() | ||
.getResource("schema.sql"); | ||
final File file = new File(url.getFile()); | ||
final String sql = Files.readString(file.toPath()); | ||
|
||
statement.execute(sql); | ||
} catch (Exception e) { | ||
LOG.error(e.getMessage(), e); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
이런 부분까지 꼼꼼하게!! 👍