Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 헤이큐
- 와끼
- AATCC
- 비리짐
- 엑셀자동서식
- 고급영어단어
- 슈퍼코딩
- 미니마카
- 핸드캐리쿠리어차이점
- 비슬론지퍼
- WHATTIMEOFTHEDAY
- TACKING
- 40HQ컨테이너
- 영어시간읽기
- 필터링후복사붙여넣기
- 웹API
- 엑셀필터복사붙여넣기
- 엑셀드래그단축키
- 자켓실측
- Armhole Drop
- 클린코드
- MERN스택
- 미국영어연음
- 봉제용어
- 암홀트롭
- 요척합의
- 지연환가료
- 나일론지퍼
- 40HQ컨테이너40GP컨테이너차이
- 우레탄지퍼
Archives
- Today
- Total
CASSIE'S BLOG
[슈퍼코딩] 95-1강 스트링 부트 Service Layer 살펴보기 본문
Service Layer and Login Tier 다 같은 말이다.
Controller에 이미 비즈니스 로직이 조금 되어있다.
Dto를 Entity로 바꾸고
Entity를 다시 Dto로 바꾸는데
이것도 사실 어떻게 보면 비즈니스 로직이라고함
Controller는 사실 이런거를 책임질 필요가 없다.
그래서 Service로 이 역할을 위임할 것이라고 함.
Controller에 Dao를 바로 사용하게됨으로써
변환하는 부분을 다 Service로 몰아감
ElectronicStoreItemService
@Service하면 컴포넌트처럼 빈으로 등록이 된다고함
ElectornicStoreController에 Dao를 없애고 그 자리에 Service가 들어갈 예정
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());
Integer idInt = Integer.parseInt(id);
ItemEntity itemEntity = electonicStoreItemRepository.findItemById(idInt);
Item item = new Item(itemEntity);
return item;
}
@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;
};
}
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());
Integer idInt = Integer.parseInt(id);
ItemEntity itemEntity = electonicStoreItemRepository.findItemById(idInt);
Item item = new Item(itemEntity);
return item;
}
@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;
};
}
위는 수정 전
Service 추가하고
private ElectronicStoreItemService electonicStoreItemService;
이 아래 생성자 없애고
public ElectronicStoreController(ElectonicStoreItemRepository electonicStoreItemRepository) {
this.electonicStoreItemRepository = electonicStoreItemRepository;
}
this.electonicStoreItemRepository = electonicStoreItemRepository;
}
이 Repository도 없애고
private ElectonicStoreItemRepository electonicStoreItemRepository;
생성자를 만들어주는데 electornicService를 매개변수로 하는 생성자를 만들어준다.
before
@GetMapping("/items")
public List<Item> findAllItem (){
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}
public List<Item> findAllItem (){
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}
after
일단 또 만들어준다.
package com.github.supercoding.service;
import com.github.supercoding.web.dto.Item;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ElectronicStoreItemService {
public List<Item> findAllItem() {
}
}
import com.github.supercoding.web.dto.Item;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class ElectronicStoreItemService {
public List<Item> findAllItem() {
}
}
package com.github.supercoding.service;
import com.github.supercoding.repository.ElectonicStoreItemRepository;
import com.github.supercoding.repository.ItemEntity;
import com.github.supercoding.web.dto.Item;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ElectronicStoreItemService {
private ElectonicStoreItemRepository electonicStoreItemRepository;
public List<Item> findAllItem() {
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}
}
import com.github.supercoding.repository.ElectonicStoreItemRepository;
import com.github.supercoding.repository.ItemEntity;
import com.github.supercoding.web.dto.Item;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ElectronicStoreItemService {
private ElectonicStoreItemRepository electonicStoreItemRepository;
public List<Item> findAllItem() {
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}
}
여기서 끝나는게 아니라 Service에 Repository로 constructor를 주입을 해야함.
package com.github.supercoding.service;
import com.github.supercoding.repository.ElectonicStoreItemRepository;
import com.github.supercoding.repository.ItemEntity;
import com.github.supercoding.web.dto.Item;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ElectronicStoreItemService {
private ElectonicStoreItemRepository electonicStoreItemRepository;
public ElectronicStoreItemService(ElectonicStoreItemRepository electonicStoreItemRepository) {
this.electonicStoreItemRepository = electonicStoreItemRepository;
}
public List<Item> findAllItem() {
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}
}
import com.github.supercoding.repository.ElectonicStoreItemRepository;
import com.github.supercoding.repository.ItemEntity;
import com.github.supercoding.web.dto.Item;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class ElectronicStoreItemService {
private ElectonicStoreItemRepository electonicStoreItemRepository;
public ElectronicStoreItemService(ElectonicStoreItemRepository electonicStoreItemRepository) {
this.electonicStoreItemRepository = electonicStoreItemRepository;
}
public List<Item> findAllItem() {
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}
}
이렇게 옮기고 controller에는 간단하게 한줄로 딱 남겨야함.
이런식으로
@GetMapping("/items")
public List<Item> findAllItem (){
return electonicStoreItemService.findAllItem();
}
public List<Item> findAllItem (){
return electonicStoreItemService.findAllItem();
}
before
@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;
}
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;
}
after
public Integer saveItem(ItemBody itemBody) {
ItemEntity itemEntity = new ItemEntity(null, itemBody.getName(), itemBody.getType(),
itemBody.getPrice(), itemBody.getSpec().getCpu(), itemBody.getSpec().getCapacity());
//이 부분 추가
return electonicStoreItemRepository.saveItem(itemEntity);
}
ItemEntity itemEntity = new ItemEntity(null, itemBody.getName(), itemBody.getType(),
itemBody.getPrice(), itemBody.getSpec().getCpu(), itemBody.getSpec().getCapacity());
//이 부분 추가
return electonicStoreItemRepository.saveItem(itemEntity);
}
실습일단 넘겨 좀 간단해서
나는 여기서 그냥 복붙만 헀잖아
public List<Item> findItemsByIds(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;
}
Set<String> IdSet = ids.stream().collect(Collectors.toSet());
List<Item> itemsfounded = items.stream().filter((item -> IdSet.contains(item.getId()))).collect(Collectors.toList());
return itemsfounded;
}
콜론 2개 중요
public List<Item> findItemsByIds(List<String> ids) {
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
List<Item> itemsfounded = itemEntities.stream()
.map(Item::new)
.filter((item -> ids.contains(item.getId()))).collect(Collectors.toList());
return itemsfounded;
}
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
List<Item> itemsfounded = itemEntities.stream()
.map(Item::new)
.filter((item -> ids.contains(item.getId()))).collect(Collectors.toList());
return itemsfounded;
}
끝 다 바꿈
package com.github.supercoding.service;
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.stereotype.Service;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class ElectronicStoreItemService {
private ElectonicStoreItemRepository electonicStoreItemRepository;
public ElectronicStoreItemService(ElectonicStoreItemRepository electonicStoreItemRepository) {
this.electonicStoreItemRepository = electonicStoreItemRepository;
}
public List<Item> findAllItem() {
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}
public Integer saveItem(ItemBody itemBody) {
ItemEntity itemEntity = new ItemEntity(null, itemBody.getName(), itemBody.getType(),
itemBody.getPrice(), itemBody.getSpec().getCpu(), itemBody.getSpec().getCapacity());
//이 부분 추가
return electonicStoreItemRepository.saveItem(itemEntity);
}
public Item findItemById(String id) {
Integer idInt = Integer.parseInt(id);
ItemEntity itemEntity = electonicStoreItemRepository.findItemById(idInt);
Item item = new Item(itemEntity);
return item;
}
public List<Item> findItemsByIds(List<String> ids) {
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
List<Item> itemsfounded = itemEntities.stream()
.map(Item::new)
.filter((item -> ids.contains(item.getId()))).collect(Collectors.toList());
return itemsfounded;
}
public void deleteItem(String id) {
Integer idInt = Integer.parseInt(id);
electonicStoreItemRepository.deleteItem(idInt);
}
public Item updateItem(String id, ItemBody itemBody) {
Integer idInt = Integer.valueOf(id);
ItemEntity itemEntity = new ItemEntity(idInt, 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;
}
}
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.stereotype.Service;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Service
public class ElectronicStoreItemService {
private ElectonicStoreItemRepository electonicStoreItemRepository;
public ElectronicStoreItemService(ElectonicStoreItemRepository electonicStoreItemRepository) {
this.electonicStoreItemRepository = electonicStoreItemRepository;
}
public List<Item> findAllItem() {
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
return itemEntities.stream().map(Item::new).collect(Collectors.toList());
}
public Integer saveItem(ItemBody itemBody) {
ItemEntity itemEntity = new ItemEntity(null, itemBody.getName(), itemBody.getType(),
itemBody.getPrice(), itemBody.getSpec().getCpu(), itemBody.getSpec().getCapacity());
//이 부분 추가
return electonicStoreItemRepository.saveItem(itemEntity);
}
public Item findItemById(String id) {
Integer idInt = Integer.parseInt(id);
ItemEntity itemEntity = electonicStoreItemRepository.findItemById(idInt);
Item item = new Item(itemEntity);
return item;
}
public List<Item> findItemsByIds(List<String> ids) {
List<ItemEntity> itemEntities = electonicStoreItemRepository.findAllItems();
List<Item> itemsfounded = itemEntities.stream()
.map(Item::new)
.filter((item -> ids.contains(item.getId()))).collect(Collectors.toList());
return itemsfounded;
}
public void deleteItem(String id) {
Integer idInt = Integer.parseInt(id);
electonicStoreItemRepository.deleteItem(idInt);
}
public Item updateItem(String id, ItemBody itemBody) {
Integer idInt = Integer.valueOf(id);
ItemEntity itemEntity = new ItemEntity(idInt, 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;
}
}
반응형
'PROGRAMMING > 슈퍼코딩 강의 정리' 카테고리의 다른 글
[슈퍼코딩]95-1강 스프링부트 Service Layer 살펴보기 (0) | 2024.01.26 |
---|---|
[슈퍼코딩] 75-1강 SQL 기본문법 익히기 V2 (0) | 2024.01.26 |
[슈퍼코딩] 94-2강 스트링 부트 Data Access Layer 좀 더 살펴보기 (0) | 2024.01.22 |
[슈퍼코딩] 94-1강 스트링 부트 Data Access Layer 좀 더 살펴보기 (0) | 2024.01.19 |
[슈퍼코딩] 85강 (여기에 postman 실습있음) (1) | 2024.01.03 |