Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/333.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 避免多次检查!=无效的_Java_Spring Boot - Fatal编程技术网

Java 避免多次检查!=无效的

Java 避免多次检查!=无效的,java,spring-boot,Java,Spring Boot,假设我有一个使用JpaRepository包更新表的代码 public User test(Long userId, UserDto userDto) { User user = findByUserId(userId); User mappedUser = modelMapper.map(userDto, User.class); if (mappedUser.getAddress() != null) { user.setAddress(mappe

假设我有一个使用JpaRepository包更新表的代码

public User test(Long userId, UserDto userDto) {
    User user = findByUserId(userId);

    User mappedUser = modelMapper.map(userDto, User.class);

    if (mappedUser.getAddress() != null) {
        user.setAddress(mappedUser.getAddress());
    }

    if (mappedUser.getContact() != null) {
        user.setContact(mappedUser.getContact());
    }

    ... // more checking if != null

    return userRepository.saveAndFlush(user);
}

有什么方法可以避免对
!=使用if语句的null
?在将其保存到数据库之前?提前感谢,我是使用spring boot的新手,在前面提到的评论中将此方法移动到你的User.class

或者,我猜用户来自REST端点? 您可以通过注释定义某些字段需要填写的内容

@NotBlank("error message")
@NotNull("error message")

使用这种方法,您可以确保只有用户输入了填充的数据

有关映射对象,可以参考mapstruct mapper。它也有更新方法。你可以参考这个链接。


它直接映射,无需编写getter和setter。这是业界使用的良好实践之一。

当您定义UserDto时,在那里添加验证,如下所示

public class UserDto{
@NotNull
String address;
}
调用该方法时,添加@Valid注释

public User test(Long userId, @Valid UserDto userDto) {}

别忘了在定义测试方法的类中添加@validated注释

“移动它”?将
setFromMappedUser(User-mapped)
添加到您的用户类中,并使其负责设置值(如果不为null),以便在应该进行检查的位置进行检查?只需
User.setAddress(mappedUser.getAddress())如何?如果在UserDto中收到的地址为空,为什么要保留以前的地址或联系人?@JBNizet如果我使用
user.setAddress(mappedUser.getAddress()),它将使用空值更新实体是的,这通常是您想要的。同样,如果UserDTO类有一个地址,用来告诉用户的地址是什么,并且调用方使用一个具有空地址的UserDTO调用该方法,为什么要忽略它将其设置为空的请求,而保留旧地址呢?看看这个解决方案,如果它不是空的,我不想抛出任何异常