【问题标题】:What rules govern using @MOdify and @Query in JPA Repository?在 JPA 存储库中使用 @MOdify 和 @Query 有哪些规则?
【发布时间】:2015-05-08 19:20:25
【问题描述】:

现在我的项目已成功完成,我们正在尝试记录经验教训。仍然让我感到困惑的是:

我们有一个地址数据库,需要在用户开始输入街道名称时自动完成。使用 JPA 存储库,我们实现了一个 PString 类(只是一个字符串的持久包装器),然后实现了这个接口:

@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);
}

尝试通过网络调用位置/搜索/findStreetNameStartingWith?street=N%20College 导致:

{"cause":null,"message":"PersistentEntity 不能为空!"}

但是,我们添加了一个控制器来调用该方法:

@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%20Col 会返回预期的三个结果。为什么直接调用该方法不起作用,但当我们通过控制器管道它时像灰狗一样运行?

【问题讨论】:

    标签: java spring hibernate jpa spring-data


    【解决方案1】:

    确保您正确配置了Spring Data REST,例如添加RepositoryRestConfiguration:

    @Configuration
    public class CustomizedRestMvcConfiguration extends RepositoryRestMvcConfiguration {
    
      @Override
      public RepositoryRestConfiguration config() {
        RepositoryRestConfiguration config = super.config();
        config.setBasePath("/custom");
        return config;
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-18
      • 2018-08-25
      • 1970-01-01
      • 1970-01-01
      • 2019-12-22
      • 2022-01-12
      • 2011-05-22
      • 2019-08-08
      相关资源
      最近更新 更多