问题
with following code I am getting error Persistence entity must not be null. what could be the mistake.
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:
If you are going to make a "search" method, use this approach:
@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);
Then use this url:
http://localhost:8080/api/districts/search/byIds?ids=1,2,3&projection=idAndName
More info about projection
If you need to use complex queries with grouping and aggregation that return DTOs you can not use "search" methods. Instead you have to implement custom controller, for example:
@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));
}
}
Where Dto
is something like this:
@Data // This is Lombok annotation (https://projectlombok.org/)
@Relation(value = "district", collectionRelation = "districts")
public class Dto {
private final Integer id;
private final String name;
}
And something like this the repo method:
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);
}
More info.
来源:https://stackoverflow.com/questions/45231260/persistence-entity-must-not-be-null