【发布时间】:2016-10-31 10:54:30
【问题描述】:
我正在使用 Spring Boot 连接到 MySQL 5 数据库(通过 JPA)以及用于服务器端的 Spring Rest。
我的 POJO:
@Entity
public class Employee {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
EmployeRespository:
@RepositoryRestResource(collectionResourceRel = "employee", path = "employee")
public interface EmployeeRepository extends PagingAndSortingRepository<Employee, Long> {
Collection<Employee> findByLastName(@Param("name") String name);
}
员工服务:
@RestController
@RequestMapping("/employee")
public class EmployeeService {
@Autowired
private EmployeeRepository employeeRepository;
@RequestMapping(value = "/findByLastName?{lastName}=", method = RequestMethod.GET)
Object getEmployees(@PathVariable String lastName) {
Collection<Employee> result = this.employeeRepository.findByLastName(lastName);
if (result == null) {
throw new EmployeeNotFoundException(lastName);
}
return result;
}
}
EmployeeNotFoundException:
public class EmployeeNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public EmployeeNotFoundException(String id) {
super("Could not find Employee " + id);
}
}
现在当调用我的 REST API 时,我得到以下结果:
这个在我的数据库中不存在并且没有抛出 EmployeeNotFoundException:
curl -X GET -H "Content-Type:application/json" http://localhost:8080/employee/search/findByLastName?name="Smith"
结果:
{
"_embedded" : {
"employee" : [ ]
},
"_links" : {
"self" : {
"href" : "http://localhost:8080/employee/search/findByLastName?name=Smith"
}
}
}
问题:
为什么会抛出我的 EmployeeNotFoundException?有没有更好的方法来实现这一点(可能还会显示 HTTP 状态代码)?
任何有关如何进行单元测试的 URL 都会很棒(以及最好的单元测试库)...
感谢您抽出宝贵时间阅读本文。
【问题讨论】:
标签: java spring rest exception spring-boot