[英]How to expose custom DTO crud repository with Spring data REST?
[英]How to work with DTO in Spring Data REST projects?
Spring Data REST自動僅公開域對象。 但大多數情況下,我們必須處理數據傳輸對象。 那么如何以SDR方式做到這一點?
如何在Spring Data REST項目中使用DTO的方法
工作的例子在這里
實體
實體必須實現可識別的接口。 例如:
@Entity
public class Category implements Identifiable<Integer> {
@Id
@GeneratedValue
private final Integer id;
private final String name;
@OneToMany
private final Set<Product> products = new HashSet<>();
// skipped
}
@Entity
public class Product implements Identifiable<Integer> {
@Id
@GeneratedValue
private final Integer id;
private final String name;
// skipped
}
預測
創建存儲庫查詢方法將返回的投影接口:
public interface CategoryProjection {
Category getCategory();
Long getQuantity();
}
它將是DTO的地下室。 在此示例中,DTO將表示Category
並且Product
的數量屬於它。
存儲庫方法
創建方法返回投影:單個,DTO列表和DTO的分頁列表。
@RepositoryRestResource
public interface CategoryRepo extends JpaRepository<Category, Integer> {
@RestResource(exported = false)
@Query("select c as category, count(p) as quantity from Category c join c.products p where c.id = ?1 group by c")
CategoryProjection getDto(Integer categoryId);
@RestResource(exported = false)
@Query("select c as category, count(p) as quantity from Category c join c.products p group by c")
List<CategoryProjection> getDtos();
@RestResource(exported = false)
@Query("select c as category, count(p) as quantity from Category c join c.products p group by c")
Page<CategoryProjection> getDtos(Pageable pageable);
}
DTO
從其界面實現DTO:
@Relation(value = "category", collectionRelation = "categories")
public class CategoryDto implements CategoryProjection {
private final Category category;
private final Long quantity;
// skipped
}
Spring Data REST渲染對象時使用注釋Relation
。
調節器
將自定義方法添加到RepositoryRestController
,它將為DTO的請求提供服務:
@RepositoryRestController
@RequestMapping("/categories")
public class CategoryController {
@Autowired private CategoryRepo repo;
@Autowired private RepositoryEntityLinks links;
@Autowired private PagedResourcesAssembler<CategoryProjection> assembler;
/**
* Single DTO
*/
@GetMapping("/{id}/dto")
public ResponseEntity<?> getDto(@PathVariable("id") Integer categoryId) {
CategoryProjection dto = repo.getDto(categoryId);
return ResponseEntity.ok(toResource(dto));
}
/**
* List of DTO
*/
@GetMapping("/dto")
public ResponseEntity<?> getDtos() {
List<CategoryProjection> dtos = repo.getDtos();
Link listSelfLink = links.linkFor(Category.class).slash("/dto").withSelfRel();
List<?> resources = dtos.stream().map(this::toResource).collect(toList());
return ResponseEntity.ok(new Resources<>(resources, listSelfLink));
}
/**
* Paged list of DTO
*/
@GetMapping("/dtoPaged")
public ResponseEntity<?> getDtosPaged(Pageable pageable) {
Page<CategoryProjection> dtos = repo.getDtos(pageable);
Link pageSelfLink = links.linkFor(Category.class).slash("/dtoPaged").withSelfRel();
PagedResources<?> resources = assembler.toResource(dtos, this::toResource, pageSelfLink);
return ResponseEntity.ok(resources);
}
private ResourceSupport toResource(CategoryProjection projection) {
CategoryDto dto = new CategoryDto(projection.getCategory(), projection.getQuantity());
Link categoryLink = links.linkForSingleResource(projection.getCategory()).withRel("category");
Link selfLink = links.linkForSingleResource(projection.getCategory()).slash("/dto").withSelfRel();
return new Resource<>(dto, categoryLink, selfLink);
}
}
當從存儲庫收到預測時,我們必須從Projection到DTO進行最終轉換,並在發送到客戶端之前將其“換行”到ResourceSupport對象。 為此,我們使用helper方法toResource
:我們創建一個新的DTO,為該對象創建必要的鏈接,然后使用該對象及其鏈接創建一個新的Resource
。
結果
請參閱Postman網站上的API文檔
燒STO
GET http://localhost:8080/api/categories/6/dto
{
"category": {
"name": "category1"
},
"quantity": 3,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/6"
},
"self": {
"href": "http://localhost:8080/api/categories/6/dto"
}
}
}
DTO列表
GET http://localhost:8080/api/categories/dto
{
"_embedded": {
"categories": [
{
"category": {
"name": "category1"
},
"quantity": 3,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/6"
},
"self": {
"href": "http://localhost:8080/api/categories/6/dto"
}
}
},
{
"category": {
"name": "category2"
},
"quantity": 2,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/7"
},
"self": {
"href": "http://localhost:8080/api/categories/7/dto"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/categories/dto"
}
}
}
DTO的分頁列表
GET http://localhost:8080/api/categories/dtoPaged
{
"_embedded": {
"categories": [
{
"category": {
"name": "category1"
},
"quantity": 3,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/6"
},
"self": {
"href": "http://localhost:8080/api/categories/6/dto"
}
}
},
{
"category": {
"name": "category2"
},
"quantity": 2,
"_links": {
"category": {
"href": "http://localhost:8080/api/categories/7"
},
"self": {
"href": "http://localhost:8080/api/categories/7/dto"
}
}
}
]
},
"_links": {
"self": {
"href": "http://localhost:8080/api/categories/dtoPaged"
}
},
"page": {
"size": 20,
"totalElements": 2,
"totalPages": 1,
"number": 0
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.