Есть небольшое CRUD приложение. Подскажите как лучше реализовать постраничный вывод данных из БД? Контролер:
@Controller
public class PartController {
private PartService partService;
@Autowired(required = true)
@Qualifier(value = "partService")
public void setBookService(PartService partService) {
this.partService = partService;
}
@RequestMapping(value = "parts", method = RequestMethod.GET)
public String listBooks(Model model){
model.addAttribute("part", new Part());
model.addAttribute("listParts", this.partService.listParts());
return "parts";
}
DAO:
public interface PartDao {
void addPart(Part part);
void updatePart(Part part);
void removePart(Long id);
Part getPartById(Long id);
List<Part> listParts();
}
public class PartDaoImpl implements PartDao {
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void addPart(Part part) {
sessionFactory.getCurrentSession().persist(part);
}
@Override
public void updatePart(Part part) {
sessionFactory.getCurrentSession().update(part);
}
@Override
public void removePart(Long id) {
Session session = sessionFactory.getCurrentSession();
Part part = session.load(Part.class, id);
if (part != null)
session.delete(part);
}
@Override
public Part getPartById(Long id) {
return sessionFactory.getCurrentSession().load(Part.class, id);
}
@Override
@SuppressWarnings("unchecked")
public List<Part> listParts() {
Session session = this.sessionFactory.getCurrentSession();
List<Part> partList = session.createQuery("from Part").list();
return partList;
}
}
И сама страница:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ taglib prefix="from" uri="http://www.springframework.org/tags/form" %>
<%@ page session="false" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Склад запчастей</title>
</head>
<body>
<h1>Список комплектующих</h1>
<c:if test="${!empty listParts}">
<table align="center" class="tg" >
<tr>
<th width="250">Название</th>
<th width="120">Необходимость</th>
<th width="120">Количество</th>
<th width="60">Править</th>
<th width="60">Удалить</th>
</tr>
<c:forEach items="${listParts}" var="part">
<tr>
<td>${part.name}</td>
<td align="center">${part.must}</td>
<td align="center">${part.count}</td>
<td><a href="<c:url value='/edit/${part.id}'/>">Править</a></td>
<td><a href="<c:url value='/remove/${part.id}'/>">Удалить</a></td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
Использовать множество методов PagingAndSortingRepository
public interface NoteRepo extends PagingAndSortingRepository<Note, Long> {
List<Note> findByIsDone(Boolean isDone);
Note findById(long id);
Page<Note> findAll(Pageable pageable);
Page<Note> findAllByIsDone(Pageable pageable, Boolean isDone);
}
Ну и в контроллере или в отдельном классе вспомогательный метод типа
private Model getPaginateModel(int countForPage, int quantityOfNotesPerPage, Model model) {
Iterable<Note> notes;
Pageable sizeOfPage = PageRequest.of(countForPage, quantityOfNotesPerPage, Direction.ASC, "date");
Page<Note> notePage = noteRepo.findAllByIsDone(sizeOfPage, true);
notes = notePage.getContent();
model.addAttribute("notes", notes);
return model;
}
Здесь частный случай, выбираются выполненные заметки, сортируются по возрастанию даты "date", можно на вход методу подать любые параметры сортировки, или фильтрации и, соответственно, реализовать любую модель постраничного вывода.
Сборка персонального компьютера от Artline: умный выбор для современных пользователей