持久性实体不能为空

时间:2017-07-21 07:09:56

标签: spring-data-rest

使用以下代码我收到错误持久性实体不能为空。可能是什么错误。

public interface DistrictRepo extends PagingAndSortingRepository<District, Integer> {

    @Query(
            "select d.districtId, d.districtName from District d where d.districtId in (:districtIds) group by d.districtId"
    )
    @RestResource(path="byList")
    List<Object[]> byList(@Param("districtIds") List<Integer> districtIds);
}

1 个答案:

答案 0 :(得分:1)

如果您要进行&#34;搜索&#34;方法,使用这种方法:

@Projection(name = "idAndName", types = {District.class})
public interface IdAndName {
    Integer getId();
    String getName();
}

@RestResource(path="byIds", rel="byIds")
@Query("select d from District d where d.districtId in (:districtIds)")
List<District> findByIds(@Param("ids") Integer... ids);

然后使用此网址:

http://localhost:8080/api/districts/search/byIds?ids=1,2,3&projection=idAndName

有关projection

的更多信息

如果您需要对返回DTO的分组和聚合使用复杂查询,则无法使用&#34; search&#34;方法。相反,您必须实施custom controller,例如:

@RepositoryRestController
@RequestMapping("/districts")
public class DistrictController {

    @Autoware
    private DistrictRepo repo;

    @GetMapping("/report")
    public ResponseEntity<?> report(@RequestParam(value = "ids") Integer... ids) {
        List<Dto> dtos = repo.getDtosByIds(ids);
        return ResponseEntity.ok(new Resources<>(dtos));
    }
}

其中Dto是这样的:

@Data // This is Lombok annotation (https://projectlombok.org/)
@Relation(value = "district", collectionRelation = "districts")
public class Dto {

    private final Integer id;
    private final String name;
}

像这样的回购方法:

public interface DistrictRepo extends PagingAndSortingRepository<District, Integer> {

    @Query("select new ...Dto(d.districtId, d.districtName) from District d where d.districtId in (:districtIds) group by d.districtId")
    @RestResource(path="byList", rel="byList")
    List<Dto> getDtosByIds(@Param("ids") Integer... ids);
}

更多info