简体   繁体   中英

Load property of entity using spring-data-jpa query methods

For example, I have entity User with fields id , active and 10 more. How could I get all active Users? Easy:

public interface UserRepository extends JpaRepository<User, Integer> {
    List<User> findAllByActiveTrue();
}

How could I load list of id of active users? I need a @Query annotation to write JPQL by myself, like this:

public interface UserRepository extends JpaRepository<User, Integer> {
    @Query("select u.id from User u where u.active = true")
    List<Integer> fetchActiveUsersIds();
}

My question is : could I name somehow a method to avoid writing JQPL by myself, like in first case?

UPDATE

I need something like this:

public interface UserRepository extends JpaRepository<User, Integer> {
    List<Integer> findAll_Id_ByActiveTrue();
}

I think that is not possible. The main purpose of Repository is to manage persistence of Domain Classes . It doesn't manage the properties independently. In the Spring Data Repositories documentation you can find a list of the methods available for CrudRepository .

You can compose your query using property extensions but it always returns the domain class for non aggregated methods.

For the specific use case you mention you'll need to use the @Query annotation.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM