程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了如何在Spring Data REST项目中使用DTO?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决如何在Spring Data REST项目中使用DTO??

开发过程中遇到如何在Spring Data REST项目中使用DTO?的问题如何解决?下面主要结合日常开发的经验,给出你关于如何在Spring Data REST项目中使用DTO?的解决方法建议,希望对你解决如何在Spring Data REST项目中使用DTO?有所启发或帮助;

EntitIEs

实体必须实现IDentifiable接口。例如:

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

projections

创建一个投影接口,存储库查询方法将返回:

public interface categoryProjection {

    category getcategory();
    Long getQuantity();
}

这将是DTO的基础。在此示例中,DTO将代表a category,而Products 的数量属于它。

Repository methods

Create方法将返回投影:一个投影,一个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
}

Relation当Spring Data REST渲染对象时使用注释。

控制者

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

从存储库收到projections时,我们必须先完成从Projection到DTO的转换,然后将其“包装”到resourceSupport对象,然后再发送给客户端。为此,我们使用辅助方法toresource:创建一个新的DTO,为此对象创建必要的链接,然后resource使用该对象及其链接创建一个新的

Result

请参阅Postman网站上的api文档

Singe DTO

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"
        }
    }
}

List of 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"
        }
    }
}

Paged List of 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,
        "@R_657_10586@lElements": 2,
        "@R_657_10586@lPages": 1,
        "number": 0
    }
}

解决方法

Spring Data REST仅自动公开域对象。但是大多数情况下,我们必须处理数据传输对象。那么如何以SDR方式做到这一点呢?

大佬总结

以上是大佬教程为你收集整理的如何在Spring Data REST项目中使用DTO?全部内容,希望文章能够帮你解决如何在Spring Data REST项目中使用DTO?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。