2017-04-03 54 views
0

我開始構建在Java中使用Spring和JPA我的第一個REST Web服務。表單驗證在休息的Webservice

現在我試圖創建的註冊服務。我有發送包含所有的實體領域什麼樣子的請求沒有問題:

@AllArgsConstructor 
@NoArgsConstructor 
@Data 
@Builder 
@Entity 
@Table(name = "users") 
public class User implements Serializable { 

private static final long serialVersionUID = 1L; 

@Id 
@GeneratedValue(strategy = GenerationType.AUTO) 
private Integer id; 

@Enumerated(EnumType.STRING) 
private Gender gender; 

@Column(name = "email") 
private String email; 

@Column(name = "login") 
private String login; 

@Column(name = "password") 
private String password; 

@Column(name = "registration_date") 
@CreatedDate 
private LocalDateTime registrationDate; 

@OneToMany(mappedBy = "bookOwner", cascade = CascadeType.ALL, fetch = FetchType.EAGER) 
private List<Book> bookList = new ArrayList<>(); 
} 

但我想只有登錄名,密碼和電子郵件字段和填充剩下的用戶信息是可以選擇我的登記表什麼情況下做 - 確認註冊後?

我考慮使用ModelMapper和各種形式的創建單獨的類,但有沒有更好的方法嗎?

回答

0

我通過我自己的使用中提到ModelMapper解決的問題。我粘貼我的代碼。如果有人感興趣,可以有用。沒有做測試,但我的數據庫看起來很好,並沒有拋出異常。

public class DTOMapper { 
     private static final ModelMapper MAPPER = new ModelMapper(); 

     private DTOMapper(){} 

     public static <S, T> T map(S source, Class<T> targetClass){ 
      return MAPPER.map(source, targetClass); 
     }  
    } 

@Service 
@Transactional 
public class SignUpService { 

    private final UserRepository userRepository; 

    @Autowired 
    public SignUpService(UserRepository userRepository) { 
     this.userRepository = userRepository; 
    } 

    public User registerUser(SignUpForm form){ 
     if(userRepository.findByLogin(form.getLogin())!=null){ 
      throw new LoginAlreadyUsedException(form.getLogin()); 
     } 

     if(userRepository.findByEmail(form.getEmail())!=null){ 
      throw new EmailAlreadyUsedException(form.getEmail()); 
     } 

     User user = DTOMapper.map(form, User.class); 

     User saved = userRepository.save(user); 

     return DTOMapper.map(saved, User.class); 
    } 
} 

@AllArgsConstructor 
@NoArgsConstructor 
@Data 
@Builder 
public class SignUpForm implements Serializable { 

    private static final long serialVersionUID = 1L; 

    @NotEmpty 
    @Size(min = 5) 
    private String login; 

    @NotEmpty 
    @Size(min = 7) 
    private String password; 

    //todo email validation 
    @NotEmpty 
    private String email; 
} 


@RestController 
public class SignUpController { 
    private static final Logger log = LoggerFactory.getLogger(SignUpController.class); 

    @Autowired 
    private SignUpService signUpService; 

    @PostMapping(value = "/signup") 
    public ResponseEntity<?> addUser(@RequestBody @Valid SignUpForm form, BindingResult errors){ 

     if(errors.hasErrors()){ 
      throw new InvalidRequestException(errors); 
     } 

     signUpService.registerUser(form); 
     return new ResponseEntity<>(form, HttpStatus.CREATED); 
    } 
}