관리 메뉴

CASSIE'S BLOG

[슈퍼코딩] 95-1강 스트링 부트 Service Layer 살펴보기 본문

PROGRAMMING/슈퍼코딩 강의 정리

[슈퍼코딩] 95-1강 스트링 부트 Service Layer 살펴보기

ITSCASSIE1107 2024. 1. 23. 16:45

 

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;

};
}

 

위는 수정 전 

 

Service 추가하고 

private ElectronicStoreItemService electonicStoreItemService;

 

이 아래 생성자 없애고

 

public ElectronicStoreController(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());
}

 

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() {
}
}

 

 

 

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());
}
}

 

여기서 끝나는게 아니라 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());
}
}

 

이렇게 옮기고 controller에는 간단하게 한줄로 딱 남겨야함.

 

이런식으로 

 

@GetMapping("/items")
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;
}

 

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);
}

 

실습일단 넘겨 좀 간단해서 

 

나는 여기서 그냥 복붙만 헀잖아

 

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;
}

 

 

 

 

 

콜론 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;
}

 

 

끝 다 바꿈

 

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;
}
}
반응형