관리 메뉴

CASSIE'S BLOG

[슈퍼코딩] 94-2강 스트링 부트 Data Access Layer 좀 더 살펴보기 본문

PROGRAMMING/슈퍼코딩 강의 정리

[슈퍼코딩] 94-2강 스트링 부트 Data Access Layer 좀 더 살펴보기

ITSCASSIE1107 2024. 1. 22. 22:42

 
⭐ElectronicStoreController에서 갈아엎는 것임 ⭐
 
 
before
 

@PostMapping("/items")
public String registerItem(@RequestBody ItemBody itemBody){
Item newItem = new Item (serialItemId++, itemBody );
items.add(newItem);
return "ID: " + newItem.getId();
}

 
 
after 
 
 
 
 
 
 

 
기존꺼 주석처리 
 
⭐after ⭐ 주석처리 이후에 지울 것임
 

@PostMapping("/items")
public String registerItem(@RequestBody ItemBody itemBody){
// Item newItem = new Item (serialItemId++, itemBody );
// items.add(newItem);
// return "ID: " + newItem.getId();

Integer itemId = electonicStoreItemRepository.saveItem(itemBody);
return "ID: " + itemId;
}

 
 
JdbcTemplate.query는 데이터를 가져올 때 쓰는 거고 update할 때는 update 메소드 써야함

변동값이 있는건 ? 표시해야하고

update같은 경우에는 RowMapper를 쓰지않고 값을 하나씩 “바로” 넣으면 된다.



jdbcTemplate.update(“INSERT INTO item(name, type, price, cpu, capacity) VALUES (?, ?, ?, ?, ?)
    itemBody.getName(), itemBody.getType(), itemBody.getPrice(),
itemBody.getSpec().getCpu(),
itemBody.getSpec().getCapcity();
”);

여기서 끝나는게 아니라 여기서 그 값이 무엇인지 알아야함

제이디비씨 쿼리로 불어야함

쿼리 같은 경우이는 rowMapper뒤에

하나만 불러오는 건 queryForObject

jdbcTemplate.queryForObject(“SELECT * FROM item WHERE name = ?”, itemEntityRowMapper, itemBody.getName());


//getCpu(); 할수가 없다. 바로 없기 때문임
spec안에 cpu있잖아

return itemEntity.getName();

public Integer saveItem(ItemBody itembody){};

{} 안에 들어가는 로직이니까


재생 실행하면 됨

다시 정리하면

ItemBody는 json값이 들어간 게 들어갔잖아

id를 바로 추적하기 위해 조회 로직도 같이 넣는거임


 ElectronicStoreItemJdbcDao에서 saveItem method 구현하라고 뜸

package com.github.supercoding.repository;

import com.github.supercoding.web.dto.Item;
import com.github.supercoding.web.dto.ItemBody;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class ElectronicStoreItemJdbcDao implements ElectonicStoreItemRepository{


private JdbcTemplate jdbcTemplate;

static RowMapper<ItemEntity> itemEntityRowMapper = ((rs, rowNum) -> (
new ItemEntity(
rs.getInt("id"),
rs.getNString("name"),
rs.getNString("type"),
rs.getInt("price"),
rs.getNString("cpu"),
rs.getNString("capacity"))));

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

@Override
public List<Item> findAllItems() {
List<ItemEntity> itemEntities = jdbcTemplate.query("SELECT * FROM item", itemEntityRowMapper);
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}

@Override
public Integer saveItem(ItemBody itemBody) {
return null;
}
}

 
 

 
 

 
 
ItemEntityMapping이 중간에 있어야 itemEntity로 매핑이 된다. 
 
 

package com.github.supercoding.repository;

import com.github.supercoding.web.dto.Item;
import com.github.supercoding.web.dto.ItemBody;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class ElectronicStoreItemJdbcDao implements ElectonicStoreItemRepository{


private JdbcTemplate jdbcTemplate;

static RowMapper<ItemEntity> itemEntityRowMapper = ((rs, rowNum) -> (
new ItemEntity(
rs.getInt("id"),
rs.getNString("name"),
rs.getNString("type"),
rs.getInt("price"),
rs.getNString("cpu"),
rs.getNString("capacity"))));

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

@Override
public List<Item> findAllItems() {
List<ItemEntity> itemEntities = jdbcTemplate.query("SELECT * FROM item", itemEntityRowMapper);
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}

@Override
public Integer saveItem(ItemBody itemBody) {
jdbcTemplate.update("INSERT INTO item(item, type, price, cpu, capacity) VALUES (?,?,?,?,?)",
itemBody.getName(),
itemBody.getType(),
itemBody.getPrice(),
itemBody.getSpec().getCpu(),
itemBody.getSpec().getCapacity()
);

jdbcTemplate.queryForObject("SELECT * FROM item WHERE item = ?", itemEntityRowMapper, itemBody.getName());

return null;
}
}

 
 
⭐여기서 이 부분 ⭐

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

 
 
ElectronicStoreItemJdbcDao 클래스에서 생성자를 통해 JdbcTemplate를 받아와서 내부의 인스턴스 변수에 할당함으로써 의존성 주입을 하고 있습니다. 이렇게 함으로써 ElectronicStoreItemJdbcDao 클래스는 외부에서 주입받은 JdbcTemplate 객체를 사용할 수 있게 되며, 클래스 내에서 JdbcTemplate에 대한 의존성이 명시적으로 주입되었습니다. 이는 코드의 유연성을 높이고, 테스트 등에서도 의존성을 쉽게 대체하거나 모의 객체를 사용할 수 있게 합니다.
 
 
⭐ RowMapper 함수형 구현체 ⭐

⭐ 여기서 ((rs, rowNum) -> ( new ItemEntity(...))) 부분이 함수형 구현체입니다. ⭐

⭐ 람다식은 함수형 인터페이스를 간결하게 구현하기 위한 표현 방식으로, (매개변수) -> { 실행코드 } 형태로 사용됩니다. 여기서 RowMapper는 단일 추상 메서드를 가지는 함수형 인터페이스이며, mapRow가 그 추상 메서드에 해당합니다. ⭐

따라서 (rs, rowNum) -> ( new ItemEntity(...)) 부분은 RowMapper 인터페이스의 mapRow 메서드를 구현한 함수형 인터페이스의 인스턴스를 생성하는 람다식입니다. 이 람다식은 ResultSet과 rowNum을 받아 ItemEntity 인스턴스를 생성하여 반환하는 역할을 합니다.


⭐ RowMapper<ItemEntity>는 RowMapper 인터페이스를 구현하는데, 반환 타입이 ItemEntity인 것을 나타냅니다. ⭐
 



where조건문 잘못해서 오류
 

 
오류 이름:
 
java.sql.SQLSyntaxErrorException: Unknown column 'item' in 'field list'
 

 
 

 


다른건 다 쉬워서 넘어가고

Update 같이해볼 예정

Entity로 먼저 바꿔 그리고 그 entity를 repository가 사용하는 것으로

itemId가 Integer아니라서 Integer로 바꿔야함

IntId = Integer.valueOf(id);


ItemEntity 필드가 Id가 Integer로 되어있어서

ItemEntity itemEntity = new ItemEntity(idInt, itemBody.getName().,,,,,, 이런 식으로 쭉 );

ItemEntity updatedItemEntity = electronicRepository.updateItemEntity(idInt, itemEntity);




before 

@PutMapping("/items/{id}")
public Item updateItem (@PathVariable String id, @RequestBody ItemBody itemBody) {


Item itemfounded = items.stream()
.filter((item) -> item.getId().equals(id))
.findFirst()
.orElseThrow(()-> new RuntimeException());

items.remove(itemfounded);

Item itemUpdated = new Item(Integer.valueOf(id), itemBody);
items.add(itemUpdated);

return itemUpdated;
};

 

after 

@PutMapping("/items/{id}")
public Item updateItem (@PathVariable String id, @RequestBody ItemBody itemBody) {

ItemEntity itemEntity = new ItemEntity(Integer.valueOf(id), itemBody.getName(), itemBody.getType(), itemBody.getPrice(),
itemBody.getSpec().getCpu(), itemBody.getSpec().getCapacity());

ItemEntity itemEntityUpdated = electonicStoreItemRepository.updateItemEntity(Integer.valueOf(id), itemEntity);

Item itemUpdated = new Item(itemEntityUpdated);

return itemUpdated;

};

 

 

 

인터페이스에 추가가되고

 

package com.github.supercoding.repository;

import com.github.supercoding.web.dto.Item;
import com.github.supercoding.web.dto.ItemBody;

import java.util.List;

public interface ElectonicStoreItemRepository {


List<Item> findAllItems();

Integer saveItem(ItemBody itemBody);

ItemEntity updateItemEntity(Integer integer, ItemEntity itemEntity);
}

 

 

 

after

 

@Override
public ItemEntity updateItemEntity(Integer idInt, ItemEntity itemEntity) {
jdbcTemplate.update("UPDATE item" +
"SET name = ?, type = ?, price = ?, cpu = ?, capacity = ?" +
"WHERE id = ?",
itemEntity.getName(), itemEntity.getType(), itemEntity.getPrice(),
itemEntity.getCpu(), itemEntity.getCapacity(), idInt);
)
return jdbcTemplate.queryForObject("SELECT * FROM item WHERE id = ?", itemEntityRowMapper, idInt);
}

 

 

⭐SQL문 너무 길면 + 표시로 쪼갤 수 있다고함.⭐

 

 

 

왜?

 

 

⭐SQL문 적을 때 공백도 잘 봐야한다.⭐

 

 

 

⭐ 필드 이름 + 필드에 해당하는 값 ⭐

 

UPDATE 쿼리에서 SET 부분에서 필드 이름을 나열하는 것이 아니라, SET 다음에 각 필드에 해당하는 값을 설정하는 것이 올바른 구문입니다. SET 다음에는 변경할 필드와 해당 값을 설정해야 합니다.

예를 들어, 다음과 같은 UPDATE 쿼리를 생각해보세요:

UPDATE item
SET name = 'NewName', type = 'NewType', price = 1000
WHERE id = 1;

 

findAllItem()과 Register() 이거 이전에 구현한 부분은 
이거는 itemDTO가 그대로 들어가서 DaoLayer까지 그대로 들어가서 
영향을 끼친거다. 
엄청 실수하는 부분중에 하나라고 함. 
이렇게 하면 안된다고해서 다시 수정한다고함. 

 

이전에 했던거를 먼저 복습해야할 것 같음. 

 

이걸 따라가면 List<Item>을 반환하도록 되어있잖아 

 

 

이렇게 Repository Layer가 Dto 즉 (=Item)을 반환하는 것은 좋지않다. 

 

 

 

ItemEntity로 실제로 ⭐  Entity클래스를 받는 것이 일반적이다. ⭐

 

before

 

package com.github.supercoding.repository;

import com.github.supercoding.web.dto.Item;
import com.github.supercoding.web.dto.ItemBody;

import java.util.List;

public interface ElectonicStoreItemRepository {


List<Item> findAllItems();

Integer saveItem(ItemBody itemBody);

ItemEntity updateItemEntity(Integer integer, ItemEntity itemEntity);
}

after

 

 

그러면 구현 부분도 다 달라져야함

 

 

일단은 이 부분따로뺀다고함. 이 부분을 Controller로 넘긴다고함. 

itemEntities.stream().map(Item::new).collect(Collectors.toList());

 

 

after Controller에서 ItemEntity -> Item으로 변환을 해주는 거지 

@GetMapping("/items")
public List<Item> findAllItem (){
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}

 

 

이걸로 넘어가서 이것도 ItemBody가넘어오는게 좀 어색하다고함

 

 before 

@PostMapping("/items")
public String registerItem(@RequestBody ItemBody itemBody){
// Item newItem = new Item (serialItemId++, itemBody );
// items.add(newItem);
// return "ID: " + newItem.getId();

Integer itemId = electonicStoreItemRepository.saveItem(itemBody);
return "ID: " + itemId;
}

 

after

이것도 그래서 ItemEntity로 바꿀 예정

 

처음에 ItemEntity같은 경우에는 BODY만 있기때문에 처음에 ID를 null로 넣기 

 

 

 

 

 

 

 

 

Dao에서 saveItem만 보면 됨 

 

package com.github.supercoding.repository;

import com.github.supercoding.web.dto.Item;
import com.github.supercoding.web.dto.ItemBody;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class ElectronicStoreItemJdbcDao implements ElectonicStoreItemRepository{


private JdbcTemplate jdbcTemplate;

static RowMapper<ItemEntity> itemEntityRowMapper = ((rs, rowNum) -> (
new ItemEntity(
rs.getInt("id"),
rs.getNString("name"),
rs.getNString("type"),
rs.getInt("price"),
rs.getNString("cpu"),
rs.getNString("capacity"))));

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

@Override
public List<ItemEntity> findAllItems() {
return jdbcTemplate.query("SELECT * FROM item", itemEntityRowMapper);

}

@Override
public Integer saveItem(ItemEntity itemEntity) {
jdbcTemplate.update("INSERT INTO item(name, type, price, cpu, capacity) VALUES (?,?,?,?,?)",
itemEntity.getName(),
itemEntity.getType(),
itemEntity.getPrice(),
itemEntity.getCpu(),
itemEntity.getCapacity()
);

ItemEntity itemEntityFound= jdbcTemplate.queryForObject("SELECT * FROM item WHERE name = ?", itemEntityRowMapper, itemEntity.getName());

return itemEntityFound.getId();
}

@Override
public ItemEntity updateItemEntity(Integer idInt, ItemEntity itemEntity) {
jdbcTemplate.update("UPDATE item " +
"SET name = ?, type = ?, price = ?, cpu = ?, capacity = ?" +
"WHERE id = ?",
itemEntity.getName(), itemEntity.getType(), itemEntity.getPrice(),
itemEntity.getCpu(), itemEntity.getCapacity(), idInt);
return jdbcTemplate.queryForObject("SELECT * FROM item WHERE id = ?", itemEntityRowMapper, idInt);
}
}

 

⭐이렇게 구현을 해야지 dto가 "직접" Dao Layer 내부까지 들어가서 영향을 끼치는 것이 아니라

그 대신에 Entity가 들어가서 실제로 Dao Layer안에서 내부적인 db에 접근도하고 리턴값도 ItemEntity가 나오게 구현해야한다고힘. 

 

⭐총정리⭐

 

클라이언트에게 전달되는 데이터 구조를 제어하려면 DTO를 사용해야하니까 데이터베이스랑 상호작용할 때는 DTO를 쓰지말고 Entity를 쓰라는말이구나 맞지
 

네, 맞습니다. 백엔드에서는 주로 데이터베이스와의 상호작용을 처리할 때 엔티티(Entity) 클래스를 사용합니다. 이 엔티티 클래스는 데이터베이스 테이블과 매핑되어 있어서, 데이터베이스와의 연동을 효율적으로 수행할 수 있습니다.

그리고 클라이언트에게 전달되는 데이터 구조를 제어하고 특정 작업을 수행하기 위해서는 DTO(데이터 전송 객체)를 사용합니다. DTO는 클라이언트와의 통신에 필요한 데이터 구조를 정의하고, 필요한 정보만을 포함시킬 수 있습니다. 이렇게 하면 클라이언트에게 불필요한 정보의 노출을 방지할 수 있습니다.

따라서 백엔드에서는 주로 엔티티 클래스를 데이터베이스와의 상호작용에 사용하고, DTO를 클라이언트와의 통신에 사용하는 것이 일반적인 설계 방식입니다.

 

 

⭐DTO는 getter, setter 메서드를 포함하며, 이 외의 비즈니스 로직은 포함하지 않습니다.

 

참고로 하기 좋은 사이트:

https://wildeveloperetrain.tistory.com/101#google_vignette

 

역할 분리를 위한 Entity, DTO 개념과 차이점

'Entity, DTO 개념과 차이점 (+ VO)' - Entity Entity 클래스는 실제 DB 테이블과 매핑되는 핵심 클래스로, 데이터베이스의 테이블에 존재하는 컬럼들을 필드로 가지는 객체입니다. (DB의 테이블과 1:1로 매

wildeveloperetrain.tistory.com

 

 

지금 오른쪽 상단에 것을 bean 으로 등록해줌

왜 인터페이스를 두고빈을 따로 구현클래스를 뒀냐 (오른쪽 상위) 의아할 수 있는데

 

 

 

만약 그 클래스를 인터페이스 없이 사용하게 되면 강한 결합임 (상속도 강한 결합에 속함)

해당 Controller는 인터페이스를 내부적으로 사용하게되어있고

그 인터페이스를 사용하는 구현클래스들이 인터페이스를 상속하게되어있다.

 

근데 디비는 다른 버전을 사용하거나 db쪽 필드가 변경되거나, 

버전 드라이버가 변경되거나 등등 변동사항이 많다.

강한결합을 통해서 매번 변동할 때마다 영향을 끼치는 것보다는 

 

이렇게 인터페이스를 하나 두고 다르게 필요한 것들이 있으면은  다른걸 차라리 구현해가지고 그걸 빈을 등록해서 내부적으로 아무 변동 없이 바꿀 수 있기 때문⭐

 

 

 

 

 

실습있는데 바빠서 넘어감

 

 

바꾸라고 하는 부분 바꾸기

 

before 

@DeleteMapping("/items/{id}")
public String deleteItemByPathId(@PathVariable String id){

Item itemfounded = items.stream()
.filter((item) -> item.getId().equals(id))
.findFirst()
.orElseThrow(()-> new RuntimeException());

items.remove(itemfounded);
return "Object with id = " + itemfounded.getId() + "has been deleted";
}

 

after 

 

 

 

 

 

⭐Repository 클래스를 별도로 만드는 이유 ⭐ 는 주로 데이터 액세스 계층을 분리하여 코드를 모듈화하고 관리하기 쉽게 하기 위함입니다. 몇 가지 이점이 있습니다:

코드의 분리 및 모듈화:

Repository 클래스를 별도로 만들면 데이터베이스와의 상호 작용이나 다른 데이터 액세스 로직을 하나의 클래스에 집중시킬 수 있습니다. 이는 코드를 논리적으로 분리하고 모듈화하여 관리하기 쉽게 만듭니다.
단일 책임 원칙(Single Responsibility Principle) 적용:

Repository 클래스를 따로 만들면 해당 클래스는 주로 데이터베이스와의 상호 작용에 집중됩니다. 이는 단일 책임 원칙을 준수하는 설계를 가능하게 합니다.
재사용성:

Repository 클래스는 여러 컨트롤러나 서비스에서 활용될 수 있습니다. 따라서 동일한 데이터 액세스 로직을 여러 곳에서 사용할 경우 재사용성이 높아집니다.
테스트 용이성:

Repository 클래스는 독립적으로 테스트하기 쉽습니다. Mocking을 통해 가상의 데이터나 데이터베이스에 대한 테스트를 쉽게 수행할 수 있습니다.
유지보수 및 확장성:

데이터 액세스 로직이 하나의 클래스에 집중되면 해당 클래스만 수정하면 되므로 유지보수가 용이해집니다. 또한, 데이터베이스 변경 또는 다른 데이터 액세스 기술로 전환할 때도 해당 클래스만 수정하면 됩니다.
이러한 이유들로 인해 일반적으로 데이터 액세스 로직은 별도의 Repository 클래스에 모듈화되어 구현되곤 합니다. 그러나 작은 프로젝트나 간단한 경우에는 별도의 Repository 클래스를 만들지 않고 컨트롤러에서 바로 데이터베이스와 상호 작용을 수행하는 경우도 있을 수 있습니다. 프로젝트의 규모나 복잡성, 팀의 개발 스타일에 따라 다를 수 있습니다.

Controller에서 비즈니스로직을 빼서 Repository랑 이분화시킨다는말이지?

⭐1. ElectronicStoreController에서 이분화해서 

after

 

package com.github.supercoding.web.controller;

import com.github.supercoding.repository.ElectonicStoreItemRepository;
import com.github.supercoding.repository.ItemEntity;
import com.github.supercoding.web.dto.Item;
import com.github.supercoding.web.dto.ItemBody;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/api")
public class ElectronicStoreController {

private ElectonicStoreItemRepository electonicStoreItemRepository;

public ElectronicStoreController(ElectonicStoreItemRepository electonicStoreItemRepository) {
this.electonicStoreItemRepository = electonicStoreItemRepository;
}

private static int serialItemId = 1;
private List<Item> items = new ArrayList<>(Arrays.asList(
new Item (String.valueOf(serialItemId++), "Apple iPhone12", "Smartphone", 1490000, "A14 Bionic", "512GB"),
new Item (String.valueOf(serialItemId++), "Galaxy S12 Ultra", "Smartphone", 1490000, "A14 Bionic", "512GB")
));


@GetMapping("/items")
public List<Item> findAllItem (){
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}

@PostMapping("/items")
public String registerItem(@RequestBody ItemBody itemBody){

ItemEntity itemEntity = new ItemEntity(null, itemBody.getName(), itemBody.getType(),
itemBody.getPrice(), itemBody.getSpec().getCpu(), itemBody.getSpec().getCapacity());

Integer itemId = electonicStoreItemRepository.saveItem(itemEntity);
return "ID: " + itemId;
}

@GetMapping("/items/{id}")
public Item findItemByPathId(@PathVariable String id ){
Item itemfounded = items.stream()
.filter((item) -> item.getId().equals(id))
.findFirst()
.orElseThrow(()-> new RuntimeException());
return itemfounded;
}

@GetMapping("/items-query")
public Item fineItemByQueryId(@RequestParam("id") String id ){
Item itemfounded = items.stream()
.filter((item) -> item.getId().equals(id))
.findFirst()
.orElseThrow(()-> new RuntimeException());
return itemfounded;
}

@GetMapping("/items-queries")
public List<Item> fineItemByQueryId(@RequestParam("id") List<String> ids ){

Set<String> IdSet = ids.stream().collect(Collectors.toSet());

List<Item> itemsfounded = items.stream().filter((item -> IdSet.contains(item.getId()))).collect(Collectors.toList());

return itemsfounded;
}

@DeleteMapping("/items/{id}")
public String deleteItemByPathId(@PathVariable String id){
//
// Item itemfounded = items.stream()
// .filter((item) -> item.getId().equals(id))
// .findFirst()
// .orElseThrow(()-> new RuntimeException());
//
// items.remove(itemfounded);


//itemEntity id Integer라서 그런가?
electonicStoreItemRepository.deleteItem(Integer.parseInt(id));

return "Object with id =" + id + "has been deleted";
}

@PutMapping("/items/{id}")
public Item updateItem (@PathVariable String id, @RequestBody ItemBody itemBody) {

ItemEntity itemEntity = new ItemEntity(Integer.valueOf(id), itemBody.getName(), itemBody.getType(), itemBody.getPrice(),
itemBody.getSpec().getCpu(), itemBody.getSpec().getCapacity());

ItemEntity itemEntityUpdated = electonicStoreItemRepository.updateItemEntity(Integer.valueOf(id), itemEntity);

Item itemUpdated = new Item(itemEntityUpdated);

return itemUpdated;

};
}

 

⭐2. ElectonicStoreItemRepository 인터페이스에 함수 정의하고 

 

package com.github.supercoding.repository;

import com.github.supercoding.web.dto.Item;
import com.github.supercoding.web.dto.ItemBody;

import java.util.List;

public interface ElectonicStoreItemRepository {


List<ItemEntity> findAllItems();

Integer saveItem(ItemEntity itemEntity);

ItemEntity updateItemEntity(Integer integer, ItemEntity itemEntity);
void deleteItem(int parseInt);

}

 

⭐3. ElectronicStoreItemJdbcDao 직접 구현한 부분 

 

//직접실습
public void deleteItem(int idInt) {
jdbcTemplate.update("DELETE FROM item WHERE id = ?", idInt);
}

 

before

@GetMapping("/items-query")
public Item fineItemByQueryId(@RequestParam("id") String id ){
Item itemfounded = items.stream()
.filter((item) -> item.getId().equals(id))
.findFirst()
.orElseThrow(()-> new RuntimeException());
return itemfounded;
}

 

after

 

@GetMapping("/items-query")
public Item fineItemByQueryId(@RequestParam("id") String id ){
// Item itemfounded = items.stream()
// .filter((item) -> item.getId().equals(id))
// .findFirst()
// .orElseThrow(()-> new RuntimeException());

Integer idInt = Integer.parseInt(id);
ItemEntity itemEntity = electonicStoreItemRepository.findItemById(idInt);
Item item = new Item(itemEntity);
return item;
}

 

 

 

 

 

인터페이스

 

package com.github.supercoding.repository;

import com.github.supercoding.web.dto.Item;
import com.github.supercoding.web.dto.ItemBody;

import java.util.List;

public interface ElectonicStoreItemRepository {


List<ItemEntity> findAllItems();

Integer saveItem(ItemEntity itemEntity);

ItemEntity updateItemEntity(Integer integer, ItemEntity itemEntity);
void deleteItem(int parseInt);


ItemEntity findItemById(Integer idInt);

}

 

구현부분

 

@Override
public ItemEntity findItemById(Integer idInt) {
return jdbcTemplate.queryForObject("SELECT * FROM item WHERE id = ?", itemEntityRowMapper, idInt);
}

 

 

실습 다함 95강으로 넘어가도 되겠어~~ 

반응형