개요
H2 데이터베이스
다운로드 및 설치
chomod 755 h2.sh
(h2/bin/h2.sh 파일에 권한을 부여)./h2.sh
jdbc:h2:~/test
(최초 한번)~/test.mv.db
파일 생성 확인 (홈 디렉토리에 생성된다)jdbc:h2:tcp://localhost/~/test
로 접속한다create table member
(
id bigint generated by default as identity,
name varchar(255),
primary key (id)
);
insert into member(name) values ('woonsik')
insert into member values (2,'hi')
현재는 사용하지 않는 고전 데이터베이스 작성법이다
//java에서 데이터베이스와 연동하기 위해서는 jdbc가 필수적이다
implementation 'org.springframework.boot:spring-boot-starter-jdbc'
//사용하는 db 클라이언트로 h2db를 사용
runtimeOnly 'com.h2database:h2'
resources:application.properties
에 경로만 입력해주면 된다
spring.datasource.url=jdbc:h2:tcp://localhost/~/test
spring.datasource.driver-class-name=org.h2.Driver
//h2데이터베이스가 아닌 경우 id, pw를 추가하는 경우도 있다
//이번 경우에는 생략
지금까지는 MemberRepository 인터페이스
의 구현을
메모리에 저정하던 MemoryMemberRepository class
를 이용해서 구현했다면
이제부터는 JdbcMemberRepository class
를 사용해서 구현 및 DB에 저장하겠다는 것
public class JdbcMemberRepository implements MemberRepository{
private final DataSource dataSource;
public JdbcMemberRepository(DataSource dataSource) {
this.dataSource = dataSource;
}
@Override
public Member save(Member member) {
String sql = "insert into member(name) values(?)";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, member.getName());
pstmt.executeUpdate();
rs = pstmt.getGeneratedKeys();
if (rs.next()) {
member.setId(rs.getLong(1));
} else {
throw new SQLException("id 조회 실패"); }
return member;
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
@Override
public Optional<Member> findById(Long id) {
String sql = "select * from member where id = ?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setLong(1, id);
rs = pstmt.executeQuery();
if (rs.next()) {
Member member = new Member();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
return Optional.of(member);
} else {
return Optional.empty();
}
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
@Override
public Optional<Member> findByName(String name) {
String sql = "select * from member where name = ?";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
rs = pstmt.executeQuery();
if(rs.next()) {
Member member = new Member();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
return Optional.of(member);
}
return Optional.empty();
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
@Override
public List<Member> findAll() {
String sql = "select * from member";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
conn = getConnection();
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
List<Member> members = new ArrayList<>();
while(rs.next()) {
Member member = new Member();
member.setId(rs.getLong("id"));
member.setName(rs.getString("name"));
members.add(member);
}
return members;
} catch (Exception e) {
throw new IllegalStateException(e);
} finally {
close(conn, pstmt, rs);
}
}
private Connection getConnection() {
return DataSourceUtils.getConnection(dataSource);
}
private void close(Connection conn, PreparedStatement pstmt, ResultSet rs)
{
try {
if (rs != null) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null) {
close(conn);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private void close(Connection conn) throws SQLException {
DataSourceUtils.releaseConnection(conn, dataSource);
}
}
위와같이 db를 이용하는 Jdbc를 작성 후 @Configuration 파일을 수정해 준다
@Configuration
public class SpringConfig {
private DataSource dataSource;
@Autowired
public SpringConfig(DataSource dataSource) {
this.dataSource = dataSource;
}
@Bean
public MemberService memberService()
{
return new MemberService(memberRepository());
}
@Bean
public MemberRepository memberRepository()
{
//return new MemoryMemberRepository();
return new JdbcMemberRepository(dataSource);
}
}
스프링 설정 파일 변경에 따른 모습