Skip to content
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

전남대 BE_안원모 1주차 과제(3단계) #184

Open
wants to merge 17 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,32 @@
# spring-gift-product

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

step 1, step 2, 그리고 step 3 가 각각 별도의 커밋 기록을 가지고 있는데 혹시 어떻게 작업해주신건지 궁금하네요...!

# spring-gift-product
## 제품 정보를 관리하는 간단한 애플리케이션
H2 데이터베이스를 사용하여 제품 정보를 저장하며, RESTful API를 통해 제품 데이터를 관리할 수 있습니다.

### 기능
- 제품에 대한 CRUD 작업 (생성, 조회, 수정, 삭제)
- H2 데이터베이스 초기화 및 샘플 데이터 삽입
- 제품 관리를 위한 RESTful API 제공
- H2 데이터베이스 콘솔을 통한 데이터베이스 관리

### REST API 사용법
Postman 또는 브라우저를 사용하여 다음 REST API 엔드포인트를 테스트할 수 있습니다:

- 모든 제품 조회: GET /products
- 특정 제품 조회: GET /products/{id}
- 제품 생성: POST /products
Body (JSON):

{
"name": "New Product",
"price": 15.99,
"description": "Description for new product"
}

제품 수정: PUT /products/{id}
Body (JSON):
{
"name": "Updated Product",
"price": 18.99,
"description": "Updated description"
}
제품 삭제: DELETE /products/{id}
2 changes: 1 addition & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ version = '0.0.1-SNAPSHOT'

java {
toolchain {
languageVersion = JavaLanguageVersion.of(21)
languageVersion = JavaLanguageVersion.of(17)
}
}

Expand Down
43 changes: 43 additions & 0 deletions src/main/java/gift/Product.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
package gift;

import java.math.BigDecimal;

public class Product {
private Long id;
private String name;
private BigDecimal price;
private String description;

// Getters and Setters
public Long getId() {
return id;
}

public void setId(Long id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public BigDecimal getPrice() {
return price;
}

public void setPrice(BigDecimal price) {
this.price = price;
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description;
}
}
42 changes: 42 additions & 0 deletions src/main/java/gift/ProductController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package gift;

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductController {

private final ProductService productService;

public ProductController(ProductService productService) {
this.productService = productService;
}

@GetMapping
public List<Product> getAllProducts() {
return productService.getAllProducts();
}

@GetMapping("/{id}")
public Product getProductById(@PathVariable Long id) {
return productService.getProductById(id);
}

@PostMapping
public void createProduct(@RequestBody Product product) {
productService.saveProduct(product);
}

@PutMapping("/{id}")
public void updateProduct(@PathVariable Long id, @RequestBody Product product) {
product.setId(id);
productService.updateProduct(product);
}

@DeleteMapping("/{id}")
public void deleteProduct(@PathVariable Long id) {
productService.deleteProduct(id);
}
}
72 changes: 72 additions & 0 deletions src/main/java/gift/ProductRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
package gift;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class ProductRepository {

private final JdbcTemplate jdbcTemplate;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

SimpleJdbcInsert 라는 것도 사용해보는 것은 어떨까요?
어떤 차이가 있는지 확인해보면 좋을 것 같아요.


public ProductRepository(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}

private static final class ProductRowMapper implements RowMapper<Product> {

@Override
public Product mapRow(ResultSet rs, int rowNum) throws SQLException {
Product product = new Product();
product.setId(rs.getLong("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getBigDecimal("price"));
product.setDescription(rs.getString("description"));
return product;
}
}
Comment on lines +20 to +31

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

잘 만들어주셨네요!
해당 로직을 lambda 형식으로도 사용할 수 있는데, 한 번 도전해볼까요?


public List<Product> findAll() {
return jdbcTemplate.query("SELECT * FROM product", new ProductRowMapper());
}

public Product findById(Long id) {
return jdbcTemplate.query(
"SELECT * FROM product WHERE id = ?",
new Object[]{id},
new ResultSetExtractor<Product>() {
@Override
public Product extractData(ResultSet rs) throws SQLException, DataAccessException {
if (rs.next()) {
Product product = new Product();
product.setId(rs.getLong("id"));
product.setName(rs.getString("name"));
product.setPrice(rs.getBigDecimal("price"));
product.setDescription(rs.getString("description"));
return product;
}
return null; // or throw an exception if the product is not found
}
}
);
}

public void save(Product product) {
jdbcTemplate.update("INSERT INTO product (name, price, description) VALUES (?, ?, ?)",
product.getName(), product.getPrice(), product.getDescription());
}

public void update(Product product) {
jdbcTemplate.update("UPDATE product SET name = ?, price = ?, description = ? WHERE id = ?",
product.getName(), product.getPrice(), product.getDescription(), product.getId());
}

public void deleteById(Long id) {
jdbcTemplate.update("DELETE FROM product WHERE id = ?", id);
}

}
35 changes: 35 additions & 0 deletions src/main/java/gift/ProductService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package gift;

import java.util.List;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

private final ProductRepository productRepository;

public ProductService(ProductRepository productRepository) {
this.productRepository = productRepository;
}

public List<Product> getAllProducts() {
return productRepository.findAll();
}

public Product getProductById(Long id) {
return productRepository.findById(id);
}

public void saveProduct(Product product) {
productRepository.save(product);
}

public void updateProduct(Product product) {
productRepository.update(product);
}

public void deleteProduct(Long id) {
productRepository.deleteById(id);
}

}
10 changes: 10 additions & 0 deletions src/main/resources/application.properties
Original file line number Diff line number Diff line change
@@ -1 +1,11 @@
spring.application.name=spring-gift
# H2 Database configuration
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password

# Initialize the database with schema.sql and data.sql
spring.sql.init.mode=always
spring.sql.init.schema-locations=classpath:schema.sql
spring.sql.init.data-locations=classpath:data.sql
2 changes: 2 additions & 0 deletions src/main/resources/data.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
INSERT INTO product (name, price, description) VALUES ('Product1', 10.00, 'Description for Product1');
INSERT INTO product (name, price, description) VALUES ('Product2', 20.00, 'Description for Product2');
6 changes: 6 additions & 0 deletions src/main/resources/schema.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
CREATE TABLE IF NOT EXISTS product (
id BIGINT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL,
description VARCHAR(255)
);