[英]Extract only certain fields using CrudRepository?
I'm using CrudRepository
to fetch Persons
from database. 我正在使用
CrudRepository
从数据库中获取Persons
。
Is it possible to only fetch certain fields from the db, instead of the full entity, using a CrudRepository mapping method? 是否可以使用CrudRepository映射方法仅从数据库中获取某些字段,而不是整个实体?
Example: I only want to extract all lastname
column fields: 示例:我只想提取所有
lastname
列字段:
interface PersonRepository extends CrudRepository<Person, Long> {
//of course this is invalid
List<String> findAllLastname();
}
@Entity
public class Person {
@Id
private Long id;
private String firstname, lastname;
}
findAllLastname()
is of course not valid, but can I achieve this? findAllLastname()
当然是无效的,但是我可以实现吗?
Giving a Query annotation with the specific SQL query should work 为查询批注提供特定的SQL查询应该可以
@Query("select p.lastName from Person p")
List<Person> getAllLastName();
You can fetch specific field just doing this: 您可以执行以下操作来获取特定字段:
@Query("select p.lastName from Person p")
List<String> getAllLastName();
But sometimes this may not work (for example for enum type ). 但是有时这可能不起作用(例如, 对于enum type )。 The best way here, IMO, is using projection as returned type, for example:
IMO最好的方法是将投影用作返回类型,例如:
public interface PersonProjection {
String getLastName();
}
@Query("select p.lastName as lastName from Person p")
List<PersonProjection> getAllPersonProjections();
In this case if you need to get, in the future, not only the lastName
but also firstName
then you simple update your PersonProjection
and the query method: 在这种情况下,如果将来您不仅需要获取
lastName
,还需要获取firstName
则可以简单地更新PersonProjection
和查询方法:
public interface PersonProjection {
String getFirstName();
String getLastName();
}
@Query("select p.firstName as firstName, p.lastName as lastName from Person p")
List<PersonProjection> getAllPersonProjections();
Note that you should use aliases of the entity fields ( p.firstName as firstName
) that correspond to names of getters in the projection. 请注意,您应该使用与投影中的吸气剂名称相对应的实体字段的别名(
p.firstName as firstName
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.