-
Notifications
You must be signed in to change notification settings - Fork 110
Expand file tree
/
Copy pathProductDao.java
More file actions
74 lines (63 loc) · 2.43 KB
/
ProductDao.java
File metadata and controls
74 lines (63 loc) · 2.43 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
package gift.model;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.util.ArrayList;
import java.util.List;
@Repository
public class ProductDao {
private final JdbcTemplate jdbcTemplate;
public ProductDao(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
//상품 테이블 생성
public void createCustomerTable(){
var sql = """
create table customer (
id bigint,
name varchar(255),
price int,
image_url varchar(255),
primary key (id)
)
""";
jdbcTemplate.execute(sql); //여닫는 과정X, throws가 안나옴(내부에서 관리) excetion 추상화 해서 제공
}
//데이터베이스 반환결과인 Result Set 객체로 변환
public RowMapper<Product> ProductRowMapper() {
return ( (resultSet, rowNum) -> {
Product product = new Product();
product.setId(resultSet.getLong("id"));
product.setName(resultSet.getString("name"));
product.setPrice(resultSet.getInt("price"));
product.setImageUrl(resultSet.getString("image_url"));
return product;
});
}
//모든 상품 리스트 반환
public List<Product> selectAllProduct(){
var sql = "select * from product";
List<Product> list = new ArrayList<>();
return jdbcTemplate.query(sql, ProductRowMapper(), list.toArray());
}
//상품 하나 반환
public Product selectProduct(Long id){
var sql = "select id, name, price, image_url from product where id = ?";
return jdbcTemplate.queryForObject(sql, ProductRowMapper(), id);
}
//상품 추가
public void insertProduct(Product product){
var sql = "insert into product (id, name, price, image_url) values (?, ?, ?, ?)";
jdbcTemplate.update(sql, product.getId(), product.getName(), product.getPrice(), product.getImageUrl());
}
//상품 삭제
public void deleteProduct(Long id){
var sql = "delete from product where id = ?";
jdbcTemplate.update(sql, id);
}
//상품 업데이트
public void updateProduct(Product product){
var sql = "update product set name = ?, price = ?, image_url = ? where id = ?";
jdbcTemplate.update(sql, product.getName(), product.getPrice(), product.getImageUrl(), product.getId());
}
}