[내일배움캠프 Spring 4기] 27일차 TIL - CRUD

서예진·2024년 1월 25일
0

오늘의 학습 키워드 📕

▸ 코드 카타
▸ CRUD


▼ 코드 카타

2024년 1월 25일 - [프로그래머스] 13 : 과일 장수


▼ CRUD

1. 프로젝트 생성

2. 5개의 패키지 생성

  • controller, service, repository, entity, dto 패키지 만들기

3. Entity

package com.sparta.members.entity;

import com.sparta.members.dto.MemberRequestDto;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Entity
@NoArgsConstructor
@Table(name = "member")
public class Member {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "username", nullable = false)
    private String username;

    @Column(name = "userid", nullable = false)
    private String userid;

    @Column(name = "userpassword", nullable = false)
    private String userpassword;

    public Member(MemberRequestDto memberRequestDto){
        this.userid = memberRequestDto.getUserid();
        this.username = memberRequestDto.getUsername();
        this.userpassword = memberRequestDto.getUserpassword();
    }
    
    public void update(MemberRequestDto memberRequestDto){
    	this.userid = memberRequestDto.getUserid();
        this.username = memberRequestDto.getUsername();
        this.userpassword = memberRequestDto.getUserpassword();
    }
}
  • entity에는 3개의 어노테이션 필수
  • @Getter, @Entity, @NoArgsConstructor
  • 이 entity 클래스에는 데이터베이스와 연결되는 식별값이 필요
  • 이 식별값에는
    @Id -> jakarta.persistence
    @GeneratedValue(strategy = GenerationType.IDENTITY) 필수
  • @Setter 쓰지말고 update 메서드 이용하기

4. Dto

package com.sparta.members.dto;

import lombok.Getter;

@Getter
public class MemberRequestDto {
    private String username;
    private String userid;
    private String userpassword;
}
package com.sparta.members.dto;

import com.sparta.members.entity.Member;
import lombok.Getter;

@Getter
public class MemberResponseDto {
    private Long id;
    private String username;
    private String userid;
    private String userpassword;

    public MemberResponseDto(Member member){
        this.id = member.getId();
        this.username = member.getUsername();
        this.userid = member.getUserid();
        this.userpassword = member.getUserpassword();
    }
}
  • RequestDto, ResponseDto 만들기
  • @Getter 필수
  • 매개변수로 받는 부분에는 RequestDto, 리턴 부분에는 ResponseDto
  • ResponseDto에는 식별값으로 정했던 변수가 존재

5. Controller

package com.sparta.members.controller;

import com.sparta.members.dto.MemberRequestDto;
import com.sparta.members.dto.MemberResponseDto;
import com.sparta.members.entity.Member;
import com.sparta.members.service.MemberService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
public class MemberController {

    private final MemberService memberService;

    @GetMapping("/members")
    public List<MemberResponseDto> getMembers(){
        return memberService.getMembers();
    }

    @PostMapping("/members")
    public MemberResponseDto saveMember(@RequestBody MemberRequestDto memberRequestDto){
        return memberService.saveMember(memberRequestDto);
    }

    @PutMapping("/members/{membersid}")
    public MemberResponseDto updateMember(@PathVariable Long membersid, @RequestBody MemberRequestDto memberRequestDto){
        return memberService.updateMember(id, memberRequestDto);
    }

    @DeleteMapping("/members/{membersid}")
    public void deleteMember(@PathVariable Long membersid){
        memberService.deleteMember(id);
    }
}
  • @RestController
    @RequiredArgsConstructor 필수
  • Service 주입
  • Create -> Post
    Read -> Get
    Update -> Put
    Delete -> Delete
  • Auto wired -> 쓰지 않음 : 최신 스프링에 와서 생성자가 하나만 있을 때는 autowired 생략 가능
  • Controller 만들 때 생성자는 무조건 하나 -> Autowired 사용할 필요 없음

6. Service

package com.sparta.members.service;

import com.sparta.members.dto.MemberRequestDto;
import com.sparta.members.dto.MemberResponseDto;
import com.sparta.members.entity.Member;
import com.sparta.members.repository.MemberRepository;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class MemberService {

    private final MemberRepository memberRepository;

    public List<MemberResponseDto> getMembers() {
        return memberRepository.findAll().stream().map(MemberResponseDto::new).toList();
    }

    @Transactional
    public MemberResponseDto saveMember(MemberRequestDto memberRequestDto) {
        //RequestDto -> Entity
        Member member = new Member(memberRequestDto);

        //DB저장 과 Entity -> Response Dto
        return new MemberResponseDto(memberRepository.save(member));
    }

    @Transactional
    public MemberResponseDto updateMember(Long id, MemberRequestDto memberRequestDto) {
        Member member = findMember(id);
        member.update(memberRequestDto);
        return new MemberResponseDto(member);
    }
    
    @Transactional
    public void deleteMember(Long id) {
        Member member = findMember(id);
        memberRepository.delete(member);
    }
    
    private Member findMember(Long id){
        return memberRepository.findById(id).orElseThrow(() -> new IllegalArgumentException("선택한 멤버는 존재하지 않습니"));
    }
}
  • @Service
    @RequiredArgsConstructor 필수
  • Repository 주입
  • Create -> save() => @Transactional
    Read -> findAll()
    Update -> findById() / set메서드로 수정 => @Transactional
    Delete -> deleteById() => @Transactional

7. Repository

package com.sparta.members.repository;

import com.sparta.members.dto.MemberResponseDto;
import com.sparta.members.entity.Member;
import org.springframework.data.jpa.repository.JpaRepository;


public interface MemberRepository extends JpaRepository<Member, Long> {
}
  • repository는 인터페이스로 만든다.

오류 해결

  • 오류가 나서 확인해보니 mysql 드라이버가 없어서 오류가 발생했음.
    따라서 아래의 코드를 build.gradle에 추가했음.
    implementation 'mysql:mysql-connector-java:8.0.32'
  • 또한, 사용할 데이터베이스에 미리 테이블을 만들어 놓지 않아서 오류가 발생함 -> 알아서 테이블을 만드는 건 없는지,,
  • application.properties > spring.datasource.url=jdbc:mysql://localhost:3306/member
    이 부분에서 데이터베이스의 url이 member가 memo로 되어있어서 오류가 발생했음
  • @PathVarible에서 URI에 있는 변수명과 @PathVariable 뒤에 나온 변수명이 같아야함 ⭐️⭐️⭐️
@PutMapping("/members/{membersid❗️}")
    public MemberResponseDto updateMember(@PathVariable Long membersid❗️, @RequestBody MemberRequestDto memberRequestDto){
        return memberService.updateMember(id, memberRequestDto);
    }
profile
안녕하세요

0개의 댓글