Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

회원가입 api 추가 #1

Merged
merged 3 commits into from
Sep 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,12 @@ dependencies {
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'com.mysql:mysql-connector-j'
annotationProcessor 'org.projectlombok:lombok'
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-validation
implementation 'org.springframework.boot:spring-boot-starter-validation:3.3.3'

testImplementation 'org.springframework.boot:spring-boot-starter-test'
testRuntimeOnly 'org.junit.platform:junit-platform-launcher'

}

tasks.named('test') {
Expand Down
24 changes: 0 additions & 24 deletions src/main/java/com/pjw/retry_view/controller/MainController.java

This file was deleted.

51 changes: 51 additions & 0 deletions src/main/java/com/pjw/retry_view/controller/UserController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package com.pjw.retry_view.controller;

import com.pjw.retry_view.dto.UserDTO;
import com.pjw.retry_view.service.UserService;
import com.pjw.retry_view.validator.UserValidator;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/users")
@RequiredArgsConstructor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Constructor의 경우 lombok을 사용하기보다는 직접 작성 하는것이 좀 더 좋습니다!

public class UserController {
private final UserService userService;
private final UserValidator userValidator;

@InitBinder
public void init(WebDataBinder binder){
binder.addValidators(userValidator);
}

@GetMapping
public String getUsers(){
String result = "";
for(UserDTO user : userService.getUserList()){
result += user;
}
return "MainController : "+result;
}

@PostMapping
public Map<String, Object> registUser(@RequestBody @Validated UserDTO user, BindingResult bindingResult){

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

response를 객체를 사용하는 구조로 바꿔보는건 어떨까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ResponseEntity를 말씀해주신게 맞을까요?

Map<String, Object> result = new HashMap<>();

if(bindingResult.hasErrors()){
result.put("msg", "failure");
result.put("result", bindingResult.getAllErrors());
}else{
result.put("msg","success");
result.put("result", userService.insertUser(user));
}

return result;
}
}
34 changes: 24 additions & 10 deletions src/main/java/com/pjw/retry_view/dto/UserDTO.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,27 +14,35 @@
public class UserDTO implements Serializable {
private Long id;
private String name;
private Integer gender;
private String phone;
private String address;
private String loginId;
private String password;
private String nickname;
private String type;
private Integer state;

private String createdBy;
private Instant created;
private String updatedBy;
private Instant updated;
/*
public UserDTO(Long id, String name, String loginId, String password, Instant created, Instant updated){
this.id = id;
this.name = name;
this.loginId = loginId;
this.password = password;
this.created = created;
this.updated = updated;
}
*/

public User toEntity(){
return User.builder()
.id(id)
.name(name)
.gender(gender)
.phone(phone)
.address(address)
.loginId(loginId)
.password(password)
.nickname(nickname)
.type(type)
.state(state)
.createdBy(createdBy)
.created(created)
.updatedBy(updatedBy)
.updated(updated)
.build();
}
Expand All @@ -44,9 +52,15 @@ public String toString() {
return "UserDTO{" +
"id=" + id +
", name='" + name + '\'' +
", gender=" + gender +
", loginId='" + loginId + '\'' +
", password='" + password + '\'' +
", nickname='" + nickname + '\'' +
", type='" + type + '\'' +
", state=" + state +
", createdBy='" + createdBy + '\'' +
", created=" + created +
", updatedBy='" + updatedBy + '\'' +
", updated=" + updated +
'}';
}
Expand Down
50 changes: 32 additions & 18 deletions src/main/java/com/pjw/retry_view/entity/User.java
Original file line number Diff line number Diff line change
@@ -1,53 +1,67 @@
package com.pjw.retry_view.entity;

import com.pjw.retry_view.dto.UserDTO;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import jakarta.persistence.*;
import lombok.*;
import org.hibernate.annotations.ColumnDefault;

import java.time.Instant;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Table(name = "user")
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(name = "NAME")
private String name;
@Column(name = "GENDER")
private Integer gender;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

gender를 INTEGER값을 이용한 이유가 있을까요? ENUM을 활용해보는건 어떨까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

평소에 코딩하던 대로 하다보니 Integer로 하게 된 것 같습니다. 해당 부분 Enum타입으로 수정해보겠습니다!

@Column(name = "PHONE")
private String phone;
@Column(name = "ADDRESS")
private String address;
@Column(name = "LOGIN_ID")
private String loginId;
@Column(name = "PASSWORD")
private String password;
@Column(name = "NICKNAME")
private String nickname;
@Column(name = "TYPE")
private String type;
@Column(name = "STATE")
private Integer state;


@Column(name = "CREATED_BY")
private String createdBy;
@Column(name = "CREATED")
private Instant created;
@Column(name = "UPDATED_BY")
private String updatedBy;
@Column(name = "UPDATED")
private Instant updated;

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

createdAt, updatedAt도 있으면 좋을 것 같습니다!

@Builder
public User(Long id, String name, String loginId, String password, Instant created, Instant updated){
this.id = id;
this.name = name;
this.loginId = loginId;
this.password = password;
this.created = created;
this.updated = updated;
}

public UserDTO toDTO(){
return UserDTO.builder()
.id(id)
.name(name)
.gender(gender)
.phone(phone)
.address(address)
.loginId(loginId)
.password(password)
.nickname(nickname)
.type(type)
.state(state)
.createdBy(createdBy)
.created(created)
.updatedBy(updatedBy)
.updated(updated)
.build();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,5 @@
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
public List<User> findAll();
public User save(User user);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional<User> save(User user);

}
13 changes: 10 additions & 3 deletions src/main/java/com/pjw/retry_view/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,26 @@
import com.pjw.retry_view.dto.UserDTO;
import com.pjw.retry_view.entity.User;
import com.pjw.retry_view.repository.UserRepository;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Transactional

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

service 전체에 transactional을 거는 이유가 있을까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

service안에 있는 모든 메소드들에 transactional을 걸어주려고 이렇게 선언하게 되었습니다

public class UserService {
@Autowired

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Autowired vs Constructor 어떤게 다를까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

생성자를 이용하면 final 멤버 변수 초기화할 수 있고, 멤버 변수의 불변성도 지킬 수 있지만 Autowired는 멤버 변수 값을 재할당할 수 있어서 불변성이 지켜지지 않습니다

private UserRepository userRepository;

public List<UserDTO> getUserList(){
List<User> list = userRepository.findAll();
List<UserDTO> userList = list.stream().map(i->i.toDTO()).toList();
return userList;
List<User> userList = userRepository.findAll();
List<UserDTO> result = userList.stream().map(user->user.toDTO()).toList();
return result;
}

public UserDTO insertUser(UserDTO userDTO){
UserDTO result = userRepository.save(userDTO.toEntity()).toDTO();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

save에서 return하는 객체가 null일 경우엔 어떻게 될까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NullException이 발생할 것 같습니다ㅠ 해당 부분 null체크 로직 추가하도록 하겠습니다!

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Optional.ofNullable(userRepository.save(userDTO.toEntity()).orElseThrow( new BussinessException());

return result;
}
}
27 changes: 27 additions & 0 deletions src/main/java/com/pjw/retry_view/validator/UserValidator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.pjw.retry_view.validator;

import com.pjw.retry_view.dto.UserDTO;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import java.util.Set;
@Component
public class UserValidator implements Validator {

@Override
public void validate(Object target, Errors errors) {
UserDTO user = (UserDTO)target;
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "field.required","이름은 필수 입력값입니다.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone", "field.required","연락처는 필수 입력값입니다.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "field.required","주소는 필수 입력값입니다.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "loginId", "field.required","로그인 아이디는 필수 입력값입니다.");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "field.required","비밀번호는 필수 입력값입니다.");
}

@Override
public boolean supports(Class<?> clazz) {
return (UserDTO.class.isAssignableFrom(clazz));
}
}
Loading