[ UserRepository 쿼리 작성 ]
@RequiredArgsConstructor @Repository public class UserRepository { private final EntityManager em; @Transactional public User save(User user) { em.persist(user); return user; }
return이 필요 없긴 한데… return 넣어주자! 재사용? 위해?
원래는 이런 코드였는데…
이 코드가
이렇게 간소하게 바뀜!
[ DTO 만들기 ]
package shop.mtcoding.blog.user; import lombok.Data; public class UserRequest { @Data public static class JoinDTO { private String username; private String password; private String email; public User toEntity() { return User.builder() .username(username) .password(password) .email(email) .build(); } } //@Builder 있어야 사용 가능 }
잠깐! User 엔티티에 @Builder가 있는지 확인했나요?
package shop.mtcoding.blog.user; import jakarta.persistence.*; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.hibernate.annotations.CreationTimestamp; import java.sql.Timestamp; @NoArgsConstructor @Data @Table(name = "user_tb") @Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Column(unique = true) private String username; private String password; private String email; @CreationTimestamp // pc -> db (날짜주입) private Timestamp createdAt; @Builder public User(Integer id, String username, String password, String email, Timestamp createdAt) { this.id = id; this.username = username; this.password = password; this.email = email; this.createdAt = createdAt; } }
[ UserController ]
@RequiredArgsConstructor @Controller public class UserController { private final UserRepository userRepository; private final HttpSession session; @PostMapping("/join") public String join(UserRequest.JoinDTO requestDTO) { userRepository.save(requestDTO.toEntity()); return "redirect:/login-form"; }
끝
+ [ 회원가입 됐을 때, 바로 로그인 되게 바꿔주자! ] → UX 상승!
회원가입이 됐으니까 바로 세션을 만들어주면 된다!
@RequiredArgsConstructor @Controller public class UserController { private final UserRepository userRepository; private final HttpSession session; @PostMapping("/join") public String join(UserRequest.JoinDTO requestDTO) { User sessionUser = userRepository.save(requestDTO.toEntity()); session.setAttribute("sessionUser", sessionUser); return "redirect:/"; }
회원가입 하자마자 세션을 줘서 바로 로그인이 자동으로 됨!! → UX 좋아짐!!
바로 로그인 됨!!!!
Share article