user8421021
user8421021

Reputation:

How to count total number of users from database table using JPA, Hibernate

I am trying to get total number of mu users from database table. I am using Spring-boot, JPA and Hibernate as provider. I am trying to get total number of users that I have stored in database table and display it in my index.html. Also I would like to do the same with my other tables classes and professors.

HomeController.java

    @Controller
    public class HomeController {

        @Autowired
        private ClassesRepository classesRepository;

        @Autowired
        private ProfessorRepository professorRepository;

        @Autowired
        private PostRepository repository;

        @Autowired
        private UserRepository userRepository;

        @RequestMapping("/dashboard")
        public String dashboardPageListClasses(Model model) {
            model.addAttribute("classes", classesRepository.findAll());
            model.addAttribute("user", userRepository.findAll());
            model.addAttribute("professor", professorRepository.findAll());
            return "dashboard";
        }
}

UserRepository.java

@Repository
public interface UserRepository extends CrudRepository<User, Long>{

}

index.html

<div class="card-content">
    <p class="category">Students</p>
    <h3 class="title">**I would like to display total number here**</h3>
</div>

Upvotes: 1

Views: 4999

Answers (2)

Abhilekh Singh
Abhilekh Singh

Reputation: 2953

You can use CrudRepository default function

long count()

Returns the number of entities available.

or write Custom Query

@Repository
public interface UserRepository extends CrudRepository<User, Long>{

    @Query("SELECT COUNT(u) FROM User u")
    Long countUsers();

}

Upvotes: 2

Amer Qarabsa
Amer Qarabsa

Reputation: 6574

CrudRepository provides a count api to count the records all you need is to add this to your controller

  model.addAttribute("count", professorRepository.count());

Upvotes: 1

Related Questions