SpringBoot combines with Thymeleaf for convenient paging.
Results the following
The background code
The project structure
1. Database Config
Hibernate automatically creates tables with Latin character set and cannot insert Chinese characters. Spring. Jpa. Properties. Hibernate. The dialect = com. Ikeguang. The paging. Config. MysqlConfig. MysqlConfig. Java code:
package com.ikeguang.paging.config;
import org.hibernate.dialect.MySQL5Dialect;
import org.springframework.stereotype.Component;
/** * @author: keguang * @date: 2019/7/16 9:58 * @version: v1.0.0 * @description: Hibernate autocreate table character set Latin cannot insert Chinese. * /
@Component
@SuppressWarnings("deprecation")
public class MysqlConfig extends MySQL5Dialect{
@Override
public String getTableTypeString(a) {
return "ENGINE=InnoDB DEFAULT CHARSET=utf8"; }}Copy the code
2. Entity class Model
package com.ikeguang.paging.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.io.Serializable;
/** * @author: keguang * @date: 2019/6/24 20:18 * @version: v1.0.0 * @description: */
@Entity
public class User implements Serializable{
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private String userName;
@Column(nullable = false)
private String passWord;
@Column(nullable = false, unique = true)
private String email;
@Column(nullable = true, unique = true)
private String nickName;
@Column(nullable = false)
private String regTime;
public User(a){}
public User(String userName, String passWord, String email, String nickName, String regTime) {
this.userName = userName;
this.passWord = passWord;
this.email = email;
this.nickName = nickName;
this.regTime = regTime;
}
// omit required getters and setters
}
Copy the code
3. Jpa operation database
UserRepository. Java code
package com.ikeguang.paging.repository;
import com.ikeguang.paging.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
/** * @author: keguang * @date: 2019/7/18 10:23 * @version: v1.0.0 * @description: */
public interface UserRepository extends JpaRepository<User.Long>{
User findById(long id);
void deleteById(long id);
}
Copy the code
4. The service layer
UserService code
package com.ikeguang.paging.service;
import com.ikeguang.paging.model.User;
import org.springframework.data.domain.Page;
/** * @author: keguang * @date: 2019/7/18 10:26 * @version: v1.0.0 * @description: */
public interface UserService {
Page<User> getUserList(int pageNum, int pageSize);
User findUserById(long id);
void save(User user);
void edit(User user);
void delete(long id);
}
Copy the code
The service implementation layer
UserServiceImpl. Java code
package com.ikeguang.paging.service.impl;
import com.ikeguang.paging.model.User;
import com.ikeguang.paging.repository.UserRepository;
import com.ikeguang.paging.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
/** * @author: keguang * @date: 2019/7/18 10:27 * @version: v1.0.0 * @description: */
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserRepository userRepository;
@Override
public Page<User> getUserList(int pageNum, int pageSize) {
Sort sort = new Sort(Sort.Direction.DESC, "id");
Pageable pageable = PageRequest.of(pageNum, pageSize, sort);
Page<User> users = userRepository.findAll(pageable);
return users;
}
@Override
public User findUserById(long id) {
return userRepository.findById(id);
}
@Override
public void save(User user) {
userRepository.save(user);
}
@Override
public void edit(User user) {
userRepository.save(user);
}
@Override
public void delete(long id) { userRepository.deleteById(id); }}Copy the code
5. The Controller layer
UserController. Java code
package com.ikeguang.paging.web;
import com.ikeguang.paging.model.User;
import com.ikeguang.paging.service.UserService;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.annotation.Resource;
import java.util.Iterator;
/** * @author: keguang * @date: 2019/7/18 10:29 * @version: v1.0.0 * @description: */
@Controller
public class UserController {
@Resource
UserService userService;
@RequestMapping("/")
public String index(a) {
return "redirect:/list";
}
@RequestMapping("/list")
public String list(Model model, @RequestParam(value = "pageNum", defaultValue = "0") int pageNum, @RequestParam(value = "pageSize", defaultValue = "2") int pageSize) {
System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = =");
Page<User> users=userService.getUserList(pageNum, pageSize);
System.out.println("Total pages" + users.getTotalPages());
System.out.println("Current page is:" + pageNum);
System.out.println("Paging data:");
Iterator<User> u = users.iterator();
while (u.hasNext()){
System.out.println(u.next().toString());
}
model.addAttribute("users", users);
return "user/list";
}
@RequestMapping("/toAdd")
public String toAdd(a) {
return "user/userAdd";
}
@RequestMapping("/add")
public String add(User user) {
userService.save(user);
return "redirect:/list";
}
@RequestMapping("/toEdit")
public String toEdit(Model model,Long id) {
User user=userService.findUserById(id);
model.addAttribute("user", user);
return "user/userEdit";
}
@RequestMapping("/edit")
public String edit(User user) {
userService.edit(user);
return "redirect:/list";
}
@RequestMapping("/delete")
public String delete(Long id) {
userService.delete(id);
return "redirect:/list"; }}Copy the code
Application.properties configuration file
Com.mysql.cj.jdbc.driver is the database Driver for mysql-connector-java. If you use com.mysql.jdbc.driver, you will get an error.
spring.datasource.url=jdbc:mysql://localhost/test? useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true spring.datasource.username=root Spring. The datasource. Password = root spring. The datasource. The driver - class - name = com. Mysql. Cj. JDBC. Driver # table does not exist, the new table spring.jpa.properties.hibernate.hbm2ddl.auto=update spring.jpa.properties.hibernate.dialect=com.ikeguang.paging.config.MysqlConfig spring.jpa.show-sql= true spring.thymeleaf.cache=falseCopy the code
Template file
Bootstrap. CSS is used here. The table in front mainly contains N pieces of Pageable data, followed by an Add button to add data. At the bottom is the Pageable part, which consists of 5 parts: home page, previous page, middle page, next page and last page.
<! DOCTYPEhtml>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8"/>
<title>userList</title>
<link rel="stylesheet" th:href="@{/css/bootstrap.css}"></link>
</head>
<body class="container">
<br/>
<h1>List of users</h1>
<br/><br/>
<div class="with:80%">
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>userName</th>
<th>passWord</th>
<th>email</th>
<th>nickName</th>
<th>regTime</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr th:each="user : ${users}">
<th scope="row" th:text="${userStat.index + 1}">1</th>
<td th:text="${user.userName}">neo</td>
<td th:text="${user.passWord}">Otto</td>
<td th:text="${user.email}">6</td>
<td th:text="${user.nickName}">6</td>
<td th:text="${user.regTime}">6</td>
<td><a th:href="@{/toEdit(id=${user.id})}">edit</a></td>
<td><a th:href="@{/delete(id=${user.id})}">delete</a></td>
</tr>
</tbody>
</table>
</div>
<div class="form-group">
<div class="col-sm-2 control-label">
<a href="/toAdd" th:href="@{/toAdd}" class="btn btn-info">add</a>
</div>
</div>
<div class="modal-footer no-margin-top">
<ul class="pagination pull-right no-margin">
<! - home page - >
<li>
<a th:href="'/list? pageNum=0'">Home page</a>
</li>
<! -- Previous Page -->
<li th:if="${users.hasPrevious()}">
<a th:href="'/list? pageNum=' + ${users.previousPageable().getPageNumber()}" th:text="Previous page"></a>
</li>
<! -- Middle page -->
<li th:each="pageNum:${#numbers.sequence(0, users.getTotalPages() - 1)}">
<a th:href="'/list? pageNum=' + ${pageNum}" th:text="${pageNum + 1}" th:if="${pageNum ne users.pageable.getPageNumber()}"></a>
<a th:href="'/list? pageNum=' + ${pageNum}" th:text="${pageNum + 1}" th:if="${pageNum eq users.pageable.getPageNumber()}" th:style="'font-weight:bold; background: #6faed9; '"></a>
</li>
<! -- Next page -->
<li th:if="${users.hasNext()}">
<a th:href="'/list? pageNum=' + ${users.nextPageable().getPageNumber()}" th:text="Next page"></a>
</li>
<! - back - >
<li>
<a th:href="'/list? pageNum=' + ${users.getTotalPages() - 1}">back</a>
</li>
</ul>
</div>
</body>
</html>
Copy the code
Code making
Github address of code: code address