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>
答案 0 :(得分:1)
CrudRepository provides a count api to count the records all you need is to add this to your controller
model.addAttribute("count", professorRepository.count());
答案 1 :(得分:1)
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();
}