在本教程中,您将学习使用 Spring Data JDBC、MySQL 和 Thymeleaf 为现有 Spring Boot 应用程序实现分页、排序和过滤/搜索功能。
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.7.3
net.codejava
ProductManager
0.0.1-SNAPSHOT
ProductManager
Spring Boot Web App
17
org.springframework.boot
spring-boot-starter-data-jdbc
org.springframework.boot
spring-boot-starter-thymeleaf
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-devtools
org.projectlombok
lombok
org.springframework.boot
spring-boot-maven-plugin
application.properties
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/sales?autoReconnect=true&useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=root
#logging.level.root=
#debug=true
logging.level.org.springframework.jdbc.core.JdbcTemplate=DEBUG
MySQL建表脚本
CREATE TABLE IF NOT EXISTS `product` (
`id` int NOT NULL AUTO_INCREMENT,
`name` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
`brand` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
`madein` varchar(45) COLLATE utf8mb4_unicode_ci NOT NULL,
`price` float NOT NULL,
PRIMARY KEY (`id`)
);
Application.java
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Product.java
package com.example.model;
import org.springframework.data.annotation.Id;
import org.springframework.data.relational.core.mapping.Table;
import lombok.Data;
@Table("product")
@Data // lomok
public class Product {
@Id
private Long id;
private String name;
private String brand;
private String madein;
private float price;
public Product() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getMadein() {
return madein;
}
public void setMadein(String madein) {
this.madein = madein;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
ProductRepository.java
package com.example.repository;
import com.example.model.Product;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface ProductRepository extends PagingAndSortingRepository {
Page findAllByNameContainingOrBrandContainingOrMadeinContaining(String name, String brand, String madein, Pageable pageable);
}
ProductController.java
package com.example.controller;
import com.example.model.Product;
import com.example.repository.ProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@Controller
public class ProductController {
private static final int[] PAGE_SIZES = {2, 5, 7, 10};
@Autowired
private ProductRepository repo;
@RequestMapping("/")
public String viewHomePage(Model model) {
// String keyword = "reebok";
String keyword = null;
/*
* if (keyword != null) { return listByPage(model, 1, "name", "asc", keyword); }
*/
return listByPage(model, 1, 2, "name", "asc", keyword);
}
@GetMapping("/page/{pageNumber}")
public String listByPage(Model model, @PathVariable("pageNumber") int currentPage, @RequestParam("pageSize") int pageSize,
@RequestParam("sortField") String sortField, @RequestParam("sortDir") String sortDir, @RequestParam(value = "keyword", required = false) String keyword) {
Sort sort = Sort.by(sortField);
sort = sortDir.equals("asc") ? sort.ascending() : sort.descending();
Pageable pageable = PageRequest.of(currentPage - 1, pageSize, sort); // 7 rows per page
Page page = null;
if (keyword != null) {
page = repo.findAllByNameContainingOrBrandContainingOrMadeinContaining(keyword, keyword, keyword, pageable);
} else {
page = repo.findAll(pageable);
}
long totalItems = page.getTotalElements();
int totalPages = page.getTotalPages();
int numberOfElements = page.getNumberOfElements();
// int currentPage = page.previousPageable().getPageNumber();
List listProducts = page.getContent();
model.addAttribute("totalItems", totalItems);
model.addAttribute("totalPages", totalPages);
model.addAttribute("currentPage", currentPage);
model.addAttribute("pageSize", pageSize);
model.addAttribute("pageSizes", PAGE_SIZES);
model.addAttribute("numberOfElements", numberOfElements);
model.addAttribute("listProducts", listProducts); // next bc of thymeleaf we make the index.html
model.addAttribute("sortField", sortField);
model.addAttribute("sortDir", sortDir);
model.addAttribute("keyword", keyword);
String reverseSortDir = sortDir.equals("asc") ? "desc" : "asc";
model.addAttribute("reverseSortDir", reverseSortDir);
return "index";
}
@RequestMapping("/new")
public String showNewProductForm(Model model) {
Product product = new Product();
model.addAttribute("product", product);
return "new_product";
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String saveProduct(@ModelAttribute("product") Product product) {
repo.save(product);
return "redirect:/";
}
@RequestMapping("/edit/{id}")
public ModelAndView showEditProductForm(@PathVariable(name = "id") Long id) {
ModelAndView modelAndView = new ModelAndView("edit_product");
Product product = repo.findById(id).get();
modelAndView.addObject("product", product);
return modelAndView;
}
@RequestMapping("/delete/{id}")
public String deleteProduct(@PathVariable(name = "id") Long id) {
repo.deleteById(id);
return "redirect:/";
}
}
index.html
Product Manager
new_product.html
Create new product
Create new product
edit_product.html
Edit product
Edit product
下载:GitHub - allwaysoft/Spring-Data-JDBC_Sorting_Paging_Search_Filter-Thymeleaf