inblog logo
|
{CODE-RYU};
    SPIRNG

    [Spring] @ManyToOne 어노테이션 4 회원가입

    류재성's avatar
    류재성
    Mar 19, 2024
    [Spring] @ManyToOne 어노테이션 4 회원가입
    Contents
    1. View 확인2. 컨트롤러3. 레파지토리
     

    1. View 확인

     
    notion image
    데이터를 받기 위해 DTO를 만든다.
     
    import lombok.Data; public class UserRequest { @Data public static class JoinDTO{ private String username; private String password; private String email; //INSERT 시에만 사용 public User toEntity(){ return User.builder() .username(username) .password(password) .email(email) .build(); } }
     
    💡
    DTO 에 toEntity 메서드를 생성한다. 이 메서드를 통해 DTO 를 통해 받은 데이터를 엔티티로 만들 수 있다. 엔티티로 만들게 되면 INSERT 할 때 persist 메서드를 사용할 수 있어 훨씬 편리하다
     

    2. 컨트롤러

     
    @PostMapping("/join") public String join(UserRequest.JoinDTO requestDTO){ userRepository.save(requestDTO.toEntity()); return "redirect:/login-form"; }
     

    3. 레파지토리

     
    @Transactional public void save(User user) { em.persist(user); }
     
    💡
    DTO를 엔티티로 만들면 쿼리를 작성하지 않아도 persist 메서드로 쉽게 INSERT 할 수 있다.
    Share article

    {CODE-RYU};

    RSS·Powered by Inblog