본문 바로가기

Programming/Spring

Spring Boot JPA를 이용한 수정하기 PUT

Spring boot 에서 JPA 를 이용하여 학생 정보를 수정해보도록 하겠습니다.

파일 구성은 이렇게 진행 했고 DB는 mysql을 사용했습니다.

 

우선 DTO을 구현 합니다. DTO는 Data Transfer Object 의 약자로 로직을 가지지 않는 데이터 객체이고, getter, setter 메소드만 가진 클래스를 의미합니다.

package com.Project.demo.DTO;

import com.Project.demo.domain.Entity.UserEntity;
import com.Project.demo.service.UserService;
import lombok.Getter;
import lombok.Setter;
import org.springframework.stereotype.Service;

@Getter
@Setter
public class UserDTO {
    private long id;
    private String name;
    private String department;
    private int cnt;
    private String role;
    private int grade;

    public UserDTO( String name, String department,int cnt, String role, int grade ){
        this.name = name;
        this.department = department;
        this.cnt = cnt;
        this.role = role;
        this.grade = grade;
    }

  

}

그 후 Entity를 만들어 줍니다.

package com.Project.demo.domain.Entity;

import com.Project.demo.DTO.UserDTO;
import com.Project.demo.service.UserService;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.transaction.annotation.Transactional;

@Getter
@Builder
@Entity
@Table(name = "user")
public class UserEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    private long id;
    private String name;
    private String department;
    private String role;
    private int cnt;
    private int grade;

    public UserEntity(){

    }
    public UserEntity( String name, String department, String role, int cnt, int grade){

        this.name =name;
        this.department = department;
        this.role = role;
        this.cnt = cnt;
        this.grade =grade;
    }
    public void update(UserDTO userDto){
        this.grade = userDto.getGrade();
        this.cnt = userDto.getCnt();
        this.role = userDto.getRole();
        this.department = userDto.getDepartment();
        this.name = userDto.getName();
    }

  
}

주입 받은 DTO를 새롭게 변경 할 수 있게 update 메소드를 만들어 줍니다.

@PutMapping("/update/{id}")
    public ResponseEntity<String> userUpdate(@PathVariable long id, @RequestBody UserDTO userDTO){
        long updatedUserId = userService.userUpdate(id, userDTO);
        return ResponseEntity.ok("User updated successfully. Updated user ID: " + updatedUserId);

    }

UserController에서는 학생의 id를 입력받아 학생을 찾습니다.

다음은 비즈니스 로직을 수행할 Service 입니다.

 

 public Long userUpdate(long id , UserDTO userDTO){
        UserEntity userEntity = userRepositroy.findById(id).orElseThrow(
                () -> new IllegalArgumentException("해당 id를 가진 학생은 없습니다.")
        );
        userEntity.update(userDTO);
        userRepositroy.save(userEntity);
        return userEntity.getId();
    }

userDTO로 해당 id 를 가지고 있는 학생을 찾고 없다면 "해당 id를 가진 학생은 없습니다" 

있으면   Entity를 userDTO로 업데이트 합니다. 

이대로 끝나면 영속성만 바뀌기 때문에 db에 적용하기 위해 save를 사용 합니다.

 

바뀐 것을 확인 할 수 있습니다.

'Programming > Spring' 카테고리의 다른 글

[JPA] 랜덤값 가져오기  (0) 2024.09.29
[Project] Builder 패턴 사용  (0) 2024.08.21
AOP #8.1~#8.2  (0) 2023.01.15
스프링 DB 접근 기술 #7.3~#7.6  (0) 2023.01.14
스프링 DB 접근 기술 #7.1~#7.3  (0) 2023.01.14