java - Spring boot,对不同的查询使用相同的实体
问题描述
我正在尝试在一个具有不同列数量的实体中设置查询结果,例如:
@Entity
public class Carta1Detalles {
@Id
private int panNorequerimiento;
private String panRutempresa;
private String panSocio;
private int panIdsolicitudegreso;
private int total;
}
我有一个包含 15 列的数据库表,我进行查询并只带了 5 列,我使用我的实体非常好。但是现在我做了另一个查询,只带来了 2 列(5 列中的 2 列),但我试图使用相同的实体,我得到一个错误,因为查询结果有不同的类型,而且它是正确的。我的问题是我如何向 Java 解释结果中的属性可以是或不是强制性的?例如,在 Angular 中,您可以这样做:
public myvariable?: string;
这 '?' 表示该值可以来自或不来自 web 服务。我想在 Java 中做类似的事情。
这是可能的?谢谢
解决方案
The best way to solve your issue is to use DTO projections.
Add all fields in the table to the entity and create a new DTO class with the relevant columns:
class Carta1ListDTO {
private final int panNorequerimiento;
private final String panRutempresa;
// Constructor and getters
}
In the query create the DTO like this
em.createQuery("SELECT new package.name.Carta1ListDTO(c.panNorequerimiento, c.panRutempresa) FROM Carta1Detalles WHERE ...");
You may use different DTOs for each use case (2 fields, 5 fields) or you create one DTO with different constructors.
If you are using Spring Data JPA there's direct support for projections in the framework.