Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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 more
Archives
Today
Total
관리 메뉴

요리사에서 IT개발자로

스파르타 부트캠프 스프링 부트 U(update)D(delete) 다락방 본문

Spring

스파르타 부트캠프 스프링 부트 U(update)D(delete) 다락방

H.S-Backend 2024. 6. 13. 11:31

User Entity

@Table(name = "USER_TABLE")
@NoArgsConstructor
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

    @Column
    private String name;
    @Column
    private Long age;

    public User(String name, Long age) {
        this.name = name;
        this.age = age;
    }

 

User를 생성할 dto생성 

@Getter
public class UserCreateDto {
    private String name;
    private Long age;
}

 

Controller

@Controller
public class UserController {

    private UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/users")
    public ResponseEntity save(@RequestBody UserCreateDto dto) {
        userService.create(dto);
        return new ResponseEntity(HttpStatus.OK);
    }

 

Serivce 

@Transactional
public void create(UserCreateDto dto) {
    User user = new User(dto.getName(), dto.getAge());
    userRepository.save(user);
}

UserCreateDto 의 Name과 age를 가져와서 user객체에 전달하고

userRepository의 save메소드를 사용하여 

user를 저장한다

 

Repository

public interface UserRepository extends JpaRepository<User, Long> {
}

 

 

생성되는것을 확인할 수 있다.


Update 

 

dto

@Getter
public class UserUpdateDto {
    private Long id;
    private String name;
}

 

entity에 update 추가

@Entity
@Table(name = "USER_TABLE")
@NoArgsConstructor
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

    @Column
    private String name;
    @Column
    private Long age;

    public User(String name, Long age) {
        this.name = name;
        this.age = age;
    }

    public void update (String name){
        this.name = name;
    }
}

 

controller

@PutMapping("/users/{id}")
public ResponseEntity update(@PathVariable Long id, @RequestBody UserUpdateDto dto) {
    userService.update(id, dto);
    return new ResponseEntity(HttpStatus.OK);
}

 

service

 @Transactional
    public void update(Long id, UserUpdateDto dto) {
        if(!Objects.equals(id, dto.getId())){
            throw new RuntimeException("수정하려는 사용자가 아닙니다");
        }

        User user = userRepository.findById(id).orElseThrow(() ->
                new RuntimeException("사용자가 존재하지 않습니다"));

            user.update(dto.getName());
//            userRepository.save(user);
    }

Objects의 equals 메소드를 사용해서

id와 UserUpdateDto안의 id를 가져와서 확인한다.

일치하지않으면 RunTimeException 하고

userRepository에 일치하는 id를 가져와서 user객체에 전달하고 

User Entity에  update를 가져와서 dto.getName() 을 하여 

해당 id의 정보를 변환

 

@Transactional 로 선언했기에 userRepository에 save를 하지않아도

DB에 데이터가 바뀌었기에 저장되는것을 확인할 수 있다.


Delete 

확인할 id dto 생성

@Getter
public class UserDeleteDto {
    private Long id;
}

 

controller

@DeleteMapping("/users/{id}")
public void delete(@PathVariable Long id, @RequestBody UserDeleteDto deleteDto) {
    userService.delete(id, deleteDto);
}

 

service

public void delete(Long id, UserDeleteDto deleteDto) {
    if(!Objects.equals(id, deleteDto.getId())){
        throw new RuntimeException("수정하려는 사용자가 아닙니다");
    }

    userRepository.deleteById(id);
}

 

@PathVariable 

url에 id를 입력한 것과 deleteDto의 id가 일치하지않으면

수정하려는 사용자가 아니라는 RuntimeException 처리를 하고

맞다면

userRepository에 deleteById 메소드를 사용하여 

삭제를 한다.(Hard Delete)

 

@Transactional 어노테이션을 설정하지 않아도
userRepository의 저장된 id를 찾아와 삭제를 하는것이기에

삭제되는것을 확인할 수 있다.


 

Soft Delete

데이터를 완전삭제하지않고 삭제처리한 흔적을 남기고

DB에 저장하여 데이터를 보관한다.

복원해야 될 경우가 생길 수 있기에 

 

Hard Delete 

DB안의 해당 데이터를 완전삭제처리 한다.

굳이 저장할 필요가 없이 완전삭제처리 해도되는 경우에 사용한다.

 

 

https://velog.io/@yhlee9753/soft-delete-%EC%99%80-hard-delete-%EB%B9%84%EA%B5%90

 

soft delete 와 hard delete 비교

출처 : https://abstraction.blog/2015/06/28/soft-vs-hard-delete- 해당 사이트의 내용을 한국어로 변환한 글입니다. soft delete 는 결국 쿼리조건이 늘어나 성능에 영향을 미치고, soft delete 는 테이

velog.io

반응형