java - 直接从函数调用中赋值变量(没有new())会引发异常吗?

cst*_*992 2 java

以下代码是大型项目的一部分.

概述是我试图使用Spring MVC访问数据库.我想根据请求更新字段,并发送有关数据库发回的值的响应.

码:

@Override
@Transactional

public EmployeeResponse update(EmployeeRequest employeeRequest) {
    Employee emp = new Employee();
    UUID empId = UUID.fromString(employeeRequest.getId());
    Employee foundEmployee = employeeRepository.findOne(empId);

    if (foundEmployee != null) {
        foundEmployee.setAddress(employeeRequest.getAddress());
        // similarly set 4 fields of foundEmployee
        emp = employeeRepository.save(foundEmployee);
    }
    EmployeeResponse response = new EmployeeResponse();
    response.setAddress(emp.getAddress());
    // similarly set 4 fields of response

    return response;

}
Run Code Online (Sandbox Code Playgroud)

我发现,没有new Employee()foundEmployee,因为是emp.我不确定,但我认为这会导致异常.我对么?

另外,请告诉我什么时候应该抛出什么异常foundEmployeenull.

其他信息 - 这是帮助显示的内容:

org.?springframework.?data.?repository.?CrudRepository

public T findOne(ID id)

Retrieves an entity by its id.

Parameters:
id - must not be null.

Returns:
the entity with the given id or null if none found

Throws:
IllegalArgumentException - if id is null
Run Code Online (Sandbox Code Playgroud)

Tim*_*sen 8

在线

Employee foundEmployee = employeeRepository.findOne(empId);
Run Code Online (Sandbox Code Playgroud)

我们可以假设EmployeeRepository.findOne()将返回一个实例Employee.这不会导致编译器错误,如果在运行时发生异常,它将在内部findOne().

关于在a的情况下你应该做什么null foundEmployee,这实际上是你必须做出的设计决定.一种选择是null让方法返回让消费者知道EmployeeRequest传入的方法有一个严重的问题.

另一种选择是创建自己的Exception,然后将其抛出null foundEmployee.

更新:

鉴于您需要将某些内容传递回UI,另一种选择是创建一个空EmployeeReponse对象并返回:

EmployeeResponse response = new EmployeeResponse();
response.setAddress(null);
response.setName(null);
Run Code Online (Sandbox Code Playgroud)

确保您的框架可以将null值编组为用户友好的内容,例如所有字段的空字符串.