[英]How to get the required fields data from an Entity to VO object using Spring Data MongoDB
在Spring Data Jpa中,我们可以灵活地将必需的字段查询结果映射到VO对象,而不会将实体对象暴露在外面。
DB Used :: mysql
@Query("SELECT new CountryVO(c.id,c.name) FROM Country c")
public List<CountryVO> getCountries();
//国家实体
public class Country{
private long id;
private String name;
@DBRef
private State state;
}
//国家实体
public class State{
private long id;
private String name;
}
//国家VO
public class CountryVO{
private long id;
private String name;
private String stateName;
}
@Query("SELECT DISTINCT c.name FROM Country c")
public List<String> getNames();
现在我的观点是我使用Spring Data mongoDB和mongoDB数据库,这里的查询方式不同,如下所示
@Query(value = "{}", fields = "{'id':1,'name':1,'state.name':1}")
List<CountryVO> getAllCountries();
在上面的查询中,我们可以在fields属性中提到我们想要的字段,剩下的字段将作为空值,但我想将输出结果映射到像Spring Data Jpa这样的VO。
请让我知道任何可能性
提前致谢
只需使用您的CountyVO
作为返回类型:
@Query(value = "{}", fields = "{'id':1,'name':1}")
List<CountryVO> getAllCountries();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.