Spring Data:何时使用Projection接口和DTO投影? [英] Spring Data: when use Projection interfaces and DTO projections?
问题描述
我有这种情况:
- 它将与
Spring Data
一起使用,并与@Entity
It about to work with
Spring Data
and working with a specific set of fields of an@Entity
这两个建议对我完全有效:
The two suggestions are totally valid for me:
-
DTO projections
-
Projection interfaces
DTO projections
Projection interfaces
更甚者,在
spring-data-examples
中两者同时出现(出于示例目的,我知道):Even more, in
spring-data-examples
appears both together (I know for sample purposes):- 因此:
- 何时必须强制使用另一种,为什么?
- 彼此之间存在绩效成本吗?
Note in the Class-based Projections (DTOs) section says the following:
定义投影的另一种方法是使用值类型DTO(数据 传输对象),其中包含以下字段的属性: 应该被取回.这些DTO类型可以完全用于 使用投影接口的方式相同,除了不使用代理 发生并且无法应用任何嵌套投影.
Another way of defining projections is by using value type DTOs (Data Transfer Objects) that hold properties for the fields that are supposed to be retrieved. These DTO types can be used in exactly the same way projection interfaces are used, except that no proxying happens and no nested projections can be applied.
似乎优点是:
except that no proxying happens
和no nested projections can be applied
推荐答案
DTO方法
Pro
- 简单而向前
Con
-
这将导致更多代码,因为您必须使用构造函数和getter/setter方法创建DTO类(除非您使用Project Lombok避免样板 DTO的代码).
It will result in more code as you have to create DTO class with constructor and getters/setters (unless you utilize Project Lombok to avoid boilerplate code for DTOs).
不能应用任何嵌套投影.
No nested projections can be applied.
投影
Pro
-
由于仅使用接口而减少了代码.
Less code as it uses only interfaces.
可以应用嵌套投影
动态投影使您可以编写一种通用存储库方法以返回 根据客户的需求,实体对象中属性的不同子集.
Dynamic projection allows you write one generic repository method to return different subset of the attributes in entity object based on client's needs.
Con
- Spring在运行时生成代理 尽管经过修剪的版本(通过Projection)从Spring层返回到客户端,但
- 查询可以将整个实体对象从数据库返回到Spring层.我不确定这个特定的缺点,希望有人在必要时编辑此答案.
- Spring generates proxy at runtime
- Query could return the entire entity object from database to Spring layer though a trimmed version (via Projection) is returned from Spring layer to client. I wasn't sure about this specific disadvantage, hoping someone to edit this answer if necessary.
如果您需要嵌套或动态投影,则可能需要使用Projection方法而不是DTO方法.
If you need nested or dynamic projection, you probably want Projection approach rather than DTO approach.
请参阅官方Spring文档有关详细信息.
这篇关于Spring Data:何时使用Projection接口和DTO投影?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
-