我使用Spring Data Rest,我无法理解为什么我的RepositoryRestController不起作用。它的代码:
@RepositoryRestController
public class Cntrl {
@Autowired
private UserDao userDao;
@RequestMapping(name = "/users/{id}/nameOne",method =
RequestMethod.GET)
@ResponseBody
public PersistentEntityResource setNameOne(@PathVariable("id") Long id, PersistentEntityResourceAssembler persistentEntityResourceAssembler){
User user = userDao.findById(id).orElseThrow(()->{
throw new ServerException("Wrong id");
});
user.setLogin("One");
userDao.save(user);
return persistentEntityResourceAssembler.toFullResource(user);
}
}
和Spring Boot启动课程:
@SpringBootApplication
@EnableWebMvc
@EnableScheduling
@EnableJpaRepositories
@EnableSpringDataWebSupport
public class Application {
public static void main(String[] args) throws Exception {
SpringApplication.run(Application.class, args);
}
}
当我去基本路径(localhost:8080 / api)一切都很好,但当发送GET请求localhost:8080 / api / users / 1 / nameOne我得到空响应,我没有其他控制器,我有用户与id 1,为什么它不起作用?
它不起作用,因为您使用的URL结构已经在Spring Data Rest上下文中具有意义。
/{repository}/{id}/{column}
URL由RepositoryPropertyReferenceController.followPropertyReference
方法处理。
/api/users/1/nameOne
表示:获取id为1的用户的nameOne
列。一个重要的注意事项是:此列应引用另一个@Entity
。这意味着如果您有一个名为“surname”的String
列,并且您点击了URL /api/users/1/name
,您将获得404,因为此列未引用另一个实体。如果您有一个名为school的列引用了School
实体并且您点击了URL /api/users/1/school
,您将获得该用户的引用学校实体。如果用户没有学校,那么您将再次获得404。
此外,如果您提供的URL未与Spring Data Rest发生冲突,则@RepositoryRestController
可用于@RequestMapping
。
您可以使用以下示例对其进行测试:
@RepositoryRestController
public class CustomRepositoryRestController {
@RequestMapping(path = "/repositoryRestControllerTest", method = RequestMethod.GET)
@ResponseBody
public String nameOne() {
return "test";
}
}
访问http://localhost:8080/repositoryRestControllerTest
我希望这个解释能为你澄清一些事情。
如果localhost:8080/api
是你的根上下文,那么localhost:8080/api/users/1/nameOne
应该是你用于用户GET的url。