@Data
public class RequestUser {
@NotNull(message = "Email cannot be null")
@Size(min = 2, message = "Email not be less than two characters")
@Email
private String email;
@NotNull(message = "Name cannot be null")
@Size(min = 2, message = "Name not be less than two characters")
private String name;
@NotNull(message = "Pwd cannot be null")
@Size(min = 8, message = "Pwd not be less than two characters")
private String pwd;
}
@Data
public class UserDto {
private String email;
private String name;
private String pwd;
private String userId;
private LocalDateTime createAt;
private String encryptedPwd;
}
public interface UserService {
UserDto createUser(UserDto userDto);
}
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService{
private final UserRepository userRepository;
@Override
public UserDto createUser(UserDto userDto) {
userDto.setUserId(UUID.randomUUID().toString());
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
UserEntity userEntity = mapper.map(userDto, UserEntity.class);
userEntity.setEncryptedPwd("encryptedPwd");
UserEntity save = userRepository.save(userEntity);
return null;
}
}
@Data
@Entity
@Table(name = "users")
public class UserEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(nullable = false, length = 50, unique = true)
private String email;
@Column(nullable = false, length = 50)
private String name;
@Column(nullable = false, unique = true)
private String userId;
@Column(nullable = false, length = 50)
private String encryptedPwd;
}
public interface UserRepository extends CrudRepository<UserEntity, Long> {
}
ModelMapper 추가
<dependency> <groupId>org.modelmapper</groupId> <artifactId>modelmapper</artifactId> <version>2.3.8</version> </dependency>
Dto > Entity로 혹은 Dto > Vo로 변환할 때 set이나 생성자를 통해서 해도 되지만 좀 더 간편하게 변경하기 위한 라이브러리
@RestController
@RequestMapping("/")
@RequiredArgsConstructor
public class UserController {
private final Environment env;
private final Greeting greeting;
private final UserService userService;
...
@PostMapping("/users")
public String createUser(@RequestBody RequestUser user){
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
UserDto userDto = mapper.map(user, UserDto.class);
userService.createUser(userDto);
return "Create User!";
}
}
...
spring:
application:
name: user-service #Eureka에 등록되는 서비스 이름
h2:
console:
enabled: true
settings:
web-allow-others: true
path: /h2-console
datasource:
driver-class-name: org.h2.Driver
url: jdbc:h2:mem:testdb
username: sa
password:
...
실제로 데이터를 전송하면 Create User!를 반환받으며
db에도 정상적으로 데이터가 들어갔다.
@RestController
@RequestMapping("/")
@RequiredArgsConstructor
public class UserController {
...
@PostMapping("/users")
public ResponseEntity createUser(@RequestBody RequestUser user){
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
UserDto userDto = mapper.map(user, UserDto.class);
userService.createUser(userDto);
return ResponseEntity.status(HttpStatus.CREATED).body(null);
}
}
String으로 Create User!
와 무조건 200 Ok를 보내는 것 보다 생성되었을 때는 201코드를 보내주는 것이 더 올바른 방법이다. 그래서 위와 같이 코드를 변경해서 다시 테스트 해보자.
정상적으로 실행됨을 알수 있다.
@Data
public class ResponseUser {
private String email;
private String name;
private String userId;
}
public interface UserService {
ResponseUser createUser(UserDto userDto);
}
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService{
private final UserRepository userRepository;
@Override
public ResponseUser createUser(UserDto userDto) {
userDto.setUserId(UUID.randomUUID().toString());
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
UserEntity userEntity = mapper.map(userDto, UserEntity.class);
userEntity.setEncryptedPwd("encryptedPwd");
UserEntity save = userRepository.save(userEntity);
ResponseUser responseUser = mapper.map(save, ResponseUser.class);
return responseUser;
}
}
@RestController
@RequestMapping("/")
@RequiredArgsConstructor
public class UserController {
...
@PostMapping("/users")
public ResponseEntity createUser(@RequestBody RequestUser user){
ModelMapper mapper = new ModelMapper();
mapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);
UserDto userDto = mapper.map(user, UserDto.class);
ResponseUser responseUser = userService.createUser(userDto);
return ResponseEntity.status(HttpStatus.CREATED).body(responseUser);
}
}
다음과 같이 수정하여 회원가입 시 return 하는 데이터를 만들어서 반환해보자.
상태코드값, 반환 데이터를 이제 우리가 반환할 수 있게 만들었다.