Home > Back-end >  how to get max(column) in a table using spring-data-jpa derived query method, where column is a numb
how to get max(column) in a table using spring-data-jpa derived query method, where column is a numb

Time:01-19

I am trying to get max(uid) from users table

public class UserEntity {
    @Id
    private Long uid;
    private String name;
    private String email;
}
@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
    Long findMaxUid();
}

I am trying to call the findMaxUid() function in the userRepository in applicationRunner method.

@SpringBootApplication
public class App{

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }

    @Bean
    ApplicationRunner applicationRunner(UserRepository userRepository) {
        return args -> {
            userRepository.save(UserEntity.builder().uid(101L).build());
            System.out.println(userRepository.findMaxUid());
        };
    }

}

I am getting below exception.

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in com.orgofarmsgroup.repository.UserRepository defined in @EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Could not create query for public abstract java.lang.Long com.orgofarmsgroup.repository.UserRepository.findMaxUid(); Reason: Failed to create query for method public abstract java.lang.Long com.orgofarmsgroup.repository.UserRepository.findMaxUid(); No property 'findMaxUid' found for type 'UserEntity'

Caused by: org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract java.lang.Long com.orgofarmsgroup.repository.UserRepository.findMaxUid(); Reason: Failed to create query for method public abstract java.lang.Long com.orgofarmsgroup.repository.UserRepository.findMaxUid(); No property 'findMaxUid' found for type 'UserEntity'
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property 'findMaxUid' found for type 'UserEntity'

CodePudding user response:

Try something like this:

@Query(value = "SELECT MAX(u.uid) FROM UserEntity u")
Long findMaxUid();

CodePudding user response:

Following up on my comment, you could try the following (disclaimer: I can't test it right now so I'm not sure this will work):

interface UidView {
  Long getUid();
} 

@Repository
public interface UserRepository extends JpaRepository<UserEntity, Long> {
  //order by uid, get the top entry having the largest uid, use a projection to only read the uid
  UidView findTopByOrderByUidDesc();

  //default method that translates the call and return type
  default Long findMaxUid() {
    UidView top = findTopByOrderByUidDesc();
    return top != null ? top.getUid() : null; 
  }
}
  • Related