问题描述
现在我的项目已成功完成,我们正在尝试记录所汲取的经验教训.仍然让我感到困惑的是以下内容:
Now that my project is successfully completed, we are trying to document lessons learned. One that still confuses me is the following:
我们有一个地址数据库,并且在用户开始输入街道名称时需要自动完成.使用JPA存储库,我们实现了一个PString类(简单地是一个String的持久包装器),然后实现了以下接口:
We have a database of addresses, and needed to autocomplete when a User started typing in a street name. Using JPA repository, we implemented a PString class (simply a persistent wrapper for a String), and then implemented this interface:
@RepositoryRestResource(collectionResourceRel = "locations", path = "locations")
public interface LocationRepository extends JpaRepository<Location, Integer>, LocationRepositoryCustom {
List<Location> findByStreetNameAndCommunity_ID(@Param("street") String streetName, @Param("commId") Integer commId);
@Modifying
@Query("select distinct x.streetName from Location x where x.streetName like :street%")
List<PString> findStreetNameStartingWith(@Param("street") String streetName);
}
尝试通过网络致电location/search/findStreetNameStartingWith?street = N%20College导致:
Trying to call locations/search/findStreetNameStartingWith?street=N%20College over the web resulted in:
{"cause":null,"message":"PersistentEntity不能为null!"}
{"cause":null,"message":"PersistentEntity must not be null!"}
但是,我们添加了一个控制器来调用该方法:
However, we added a controller to call the method:
@RestController
@RequestMapping("/custom/locations")
public class LocationController {
@Autowired
private LocationRepository repo;
@RequestMapping(value = "/findStreetNamesStartingWith", method=RequestMethod.GET)
public List<PString> findStreetNameStartingWith(
@Param("streetName") String streetName) {
return repo.findStreetNameStartingWith(streetName);
}
}
调用/custom/locations/findStreetNamesStartingWith?streetName = N%20Coll返回预期的三个结果.为什么直接调用该方法不起作用,但是通过控制器通过管道运行时却像灵缇一样运行?
Calling /custom/locations/findStreetNamesStartingWith?streetName=N%20Coll returns the expected three results. Why does the method not work if called directly, but runs like a greyhound when we pipe it through a controller?
推荐答案
确保已配置 Spring Data REST ,例如添加RepositoryRestConfiguration
:
Make sure you configured Spring Data REST properly, like adding the RepositoryRestConfiguration
:
@Configuration
public class CustomizedRestMvcConfiguration extends RepositoryRestMvcConfiguration {
@Override
public RepositoryRestConfiguration config() {
RepositoryRestConfiguration config = super.config();
config.setBasePath("/custom");
return config;
}
}
这篇关于在JPA存储库中使用@MOdify和@Query有哪些规则支配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!