관리 메뉴

moozi

ServiceImpl 본문

Spring Boot JPA

ServiceImpl

moozi 2022. 5. 30. 15:27
package com.mycompany.memo.service;
import com.mycompany.memo.dto.MemoDTO;
import com.mycompany.memo.entity.Memo;
import com.mycompany.memo.repository.MemoRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

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

@Service
@Log4j2
@RequiredArgsConstructor
public class MemoServiceImpl implements MemoService{
    private final MemoRepository repository;//자동주입

    //목록
    @Override
    public List<MemoDTO> getList() {
        //repository호출
       List<Memo> result= repository.findAll();// select실행
       List<MemoDTO> list=result.stream().map(memo->entityToDto(memo)).collect(Collectors.toList());
       return list;
    }
    //등록
    @Override
    public Long register(MemoDTO dto) {
        //repository호출
        Memo memo=dtoToEntity(dto);
        repository.save(memo);// insert실행
        return memo.getMno();
    }

    @Override
    public MemoDTO read(Long mno) {
        //repository호출
        Optional<Memo> result=repository.findById(mno);
//        if(result.isPresent()){
//            return entityToDto(result.get());
//        }else{
//            return null;
//        }

        return result.isPresent()?entityToDto(result.get()):null;
    }

    @Override
    public void modify(MemoDTO dto) {
        //repository호출
        Optional<Memo> result = repository.findById(dto.getMno());
        if(result.isPresent()){
            Memo entity=result.get();
            entity.changeTitle(dto.getTitle());//title변경
            entity.changeContent(dto.getContent());//content변경
            repository.save(entity);
        }

    }

    @Override
    public void remove(Long mno) {
        //repository호출
        repository.deleteById(mno);
    }
}

'Spring Boot JPA' 카테고리의 다른 글

View  (0) 2022.05.30
Controller  (0) 2022.05.30
Service  (0) 2022.05.30
Repository  (0) 2022.05.30
Entity, DTO  (0) 2022.05.30
0 Comments
댓글쓰기 폼