코딩 노트
데이터베이스 조회 최종 형태2(product) 본문
예제는 Product 테이블 사용(회원가입 프로그램)
0. 자바와 데이터베이스를 연결해 주는 도구 클래스 형태로 편하게 구현
public class JdbcUtils {
//연결 정보를 상수로 저장
public static final String driver = "oracle.jdbc.OracleDriver";
public static final String url = "jdbc:oracle:thin:@localhost:1521:xe";
public static final String username = "C##KH";
public static final String password = "KH";
//실행도구 생성 메소드
public static JdbcTemplate getJdbcTemplate() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
return jdbcTemplate;
}
}
1. 조회 결과 중 한 줄을 담을 객체 (DTO) 생성
멤버필드, setter/getter, 기본 생성자, toString();
public class ProductDto {
//필드는 조회 결과와 동일하게 구현
private int no;
private String name;
private String type;
private int price;
private Date made;
private Date expire;
//생성자 만들 때 기본생성자를 만들어야 하니 체크 다 풀기
//생성자를 만들고 싶다면 기본생성자는 무조건 만들고 또 만들어야 함
public ProductDto() {
super();
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
~~~
~~~
~~~
public Date getExpire() {
return expire;
}
public void setExpire(Date expire) {
this.expire = expire;
}
@Override
public String toString() {
return "ProductDto [no=" + no + ", name=" + name + ", type=" + type + ", price=" + price + ", made=" + made
+ ", expire=" + expire + "]";
}
}
2. 조회 결과를 DTO에 옮겨 담는 방법을 가진 객체(Mapper) 생성
//spring RowMapper를 임포트 해야 함
//sql.date를 임포트 해야함
public class ProductMapper implements RowMapper<ProductDto> {
@Override
public ProductDto mapRow(ResultSet rs, int idx) throws SQLException {
// rs의 내용을 ProductDto에 옮겨담는 코드를 작성
ProductDto dto = new ProductDto(); //담을 수 있는 객체 생성
//데이터베이스 조회결과에서 name라는 컬럼의 값을 스트링형태로 꺼내겠다.
dto.setNo(rs.getInt("no"));
dto.setName(rs.getString("name"));
dto.setType(rs.getString("type"));
dto.setPrice(rs.getInt("price"));
dto.setMade(rs.getDate("made"));
dto.setMade(rs.getDate("expire"));
return dto;
}
}
3. 데이터에 접근하도록 DB접근 관련 로직을 모아둔 객체(DAO) 생성
public class ProductDao {
public void insert(ProductDto dto) {
String sql = "insert into product("
+ "no, name, type, price, made, expire"
+ ") values("
+ "product_seq.nextval, ?, ?, ?, ?, ?"//DTO가 Date인 경우
// + "product_seq.nextval, ?, ?, ?, to_date(?,'yyyy-mm-dd'), to_date(?,'yyyy-mm-dd')"//만약 DTO가 문자열이면
+ ")";
Object[] data = {
dto.getName(), dto.getType(), dto.getPrice(),
dto.getMade(), dto.getExpire()
};
JdbcTemplate jdbcTemplate = JdbcUtils.getJdbcTemplate();
jdbcTemplate.update(sql, data);
}
}
4. 메인 클래스에 구현
public static void main(String[] args) {
//상품 등록 프로그램
//데이터 준비
ProductDto dto = new ProductDto();
dto.setName("테스트");
dto.setType("주류");
dto.setPrice(5000);
dto.setMade(Date.valueOf("2022-07-01"));//문자열 -> Date
dto.setExpire(Date.valueOf("2022-12-31"));//문자열 -> Date
//DB처리
ProductDao dao = new ProductDao();
dao.insert(dto);
System.out.println("상품 등록 완료");
}
'Database' 카테고리의 다른 글
데이터베이스 외래키 (0) | 2023.08.01 |
---|---|
데이터베이스 - 수정 (0) | 2023.07.25 |
데이터베이스 조회 최종 형태1(member) (0) | 2023.07.24 |
데이터베이스6 - 모듈화 (0) | 2023.07.24 |
데이터베이스5 - JDBC (0) | 2023.07.21 |