标签:bin dso collect obj pre types result message nbsp
所有的JavaBean和DTO的互相转换接口,JavaBean转化成DTO或者DTO转换JavaBean:
public abstract class Converter<A, B> { protected abstract B doForward(A a); protected abstract A doBackward(B b); }
一个JavaBean:
import lombok.Data; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Data @Document(collection = "user") public class User { @Id private ObjectId id; private String username; private String password; }
对应的DTO,无参构造方法,以及全部参数方法of,以及私有静态内部类继承抽象类Convert并实现两个转换方法:
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.beans.BeanUtils; import study.Converter; import javax.validation.constraints.NotNull; @NoArgsConstructor @AllArgsConstructor(staticName = "of") @Data public class UserDTO { /** * AllArgsConstructor注解和NotNull注解配合使用,参数不为null */ @NotNull(message = "username is null") private String username; @NotNull(message = "password is null") private String password; public User convertToUser(){ UserDTOConvert userDTOConvert = new UserDTOConvert(); User convert = userDTOConvert.doForward(this); return convert; } public UserDTO convertFor(User user){ UserDTOConvert userDTOConvert = new UserDTOConvert(); UserDTO convert = userDTOConvert.doBackward(user); return convert; } private static class UserDTOConvert extends Converter<UserDTO, User> { @Override protected User doForward(UserDTO userDTO) { User user = new User(); BeanUtils.copyProperties(userDTO,user); return user; } @Override protected UserDTO doBackward(User user) { UserDTO userDTO = new UserDTO(); BeanUtils.copyProperties(user,userDTO); return userDTO; } } }
Controller中一个方法接受DTO参数,使用注解@Valid配合DTO属性上注解@NotNull使用;
接受参数,持久化,返回对象,如此优雅。
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; @RestController @RequestMapping(value = "/api/user") public class UserController { @Autowired private UserService userService; @PostMapping public UserDTO addUser(@Valid UserDTO userDTO){ User user = userDTO.convertToUser(); User addUser = userService.addUser(user); UserDTO result = userDTO.convertFor(addUser); return result; } }
来源:
https://www.itcodemonkey.com/article/6309.html?tdsourcetag=s_pctim_aiomsg
标签:bin dso collect obj pre types result message nbsp
原文地址:https://www.cnblogs.com/theRhyme/p/10529456.html