I'm using CrudRepository
to fetch Persons
from database.
Is it possible to only fetch certain fields from the db, instead of the full entity, using a CrudRepository mapping method?
Example: I only want to extract all lastname
column fields:
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?
Giving a Query annotation with the specific SQL query should work
@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 ). The best way here, IMO, is using projection as returned type, for example:
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:
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.