Spring Data JPA、MySQL 和 Thymeleaf 实现分页、排序和过滤/搜索功能

 在本教程中,您将学习使用 Spring Data JPA、Hibernate、MySQL 和 Thymeleaf 为现有 Spring Boot 应用程序实现分页、排序和过滤/搜索功能。

Spring Data JPA、MySQL 和 Thymeleaf 实现分页、排序和过滤/搜索功能_第1张图片

 Spring Data JPA、MySQL 和 Thymeleaf 实现分页、排序和过滤/搜索功能_第2张图片

 Spring Data JPA、MySQL 和 Thymeleaf 实现分页、排序和过滤/搜索功能_第3张图片

pom.xml



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.7.RELEASE
         
    
    net.codejava
    ProductManagerSortingPagingSearchFilter
    0.0.1-SNAPSHOT
    ProductManagerSortingPagingSearchFilter
    Spring Boot Web App

    
        1.8
    

    
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
            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.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=

spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true


ProductManagerApplication.java

package net.codejava;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProductManagerApplication {

	public static void main(String[] args) {
		SpringApplication.run(ProductManagerApplication.class, args);
	}

}

Product.java

package net.codejava;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class Product {

	private Long id;
	private String name;
	private String brand;
	private String madein;
	private float price;

	protected Product() {
	}

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	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 net.codejava;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
// import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.PagingAndSortingRepository;

// public interface ProductRepository extends JpaRepository {

public interface ProductRepository extends PagingAndSortingRepository {

	@Query("SELECT p FROM Product p WHERE " + "CONCAT(p.id, ' ', p.name, ' ' , p.brand, ' ' , p.madein, ' ' , p.price)"
			+ "LIKE %?1%")
	public Page findAll(String keyword, Pageable pageable);

}

ProductService.java

package net.codejava;

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;

@Service
public class ProductService {

	@Autowired
	private ProductRepository repo;

	public Page listAll(int pageNumber, String sortField, String sortDir, String keyword) {

		Sort sort = Sort.by(sortField);
		sort = sortDir.equals("asc") ? sort.ascending() : sort.descending();

		Pageable pageable = PageRequest.of(pageNumber - 1, 7, sort); // 7 rows per page

		if (keyword != null) {
			return repo.findAll(keyword, pageable);
		}
		return repo.findAll(pageable);
	}

	public void save(Product product) {
		repo.save(product);
	}

	public Product get(Long id) {
		return repo.findById(id).get();
	}

	public void delete(Long id) {
		repo.deleteById(id);
	}
}

AppController.java

package net.codejava;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.repository.query.Param;
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.servlet.ModelAndView;

import java.util.List;

@Controller
public class AppController {

	@Autowired
	private ProductService service;

	@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, "name", "asc", keyword);

	}

	@GetMapping("/page/{pageNumber}")
	public String listByPage(Model model, @PathVariable("pageNumber") int currentPage,
			@Param("sortField") String sortField, @Param("sortDir") String sortDir, @Param("keyword") String keyword) {

		Page page = service.listAll(currentPage, sortField, sortDir, keyword);

		long totalItems = page.getTotalElements();
		int totalPages = page.getTotalPages();
		// int currentPage = page.previousPageable().getPageNumber();

		List listProducts = page.getContent();

		model.addAttribute("totalItems", totalItems);
		model.addAttribute("totalPages", totalPages);
		model.addAttribute("currentPage", currentPage);
		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) {
		service.save(product);

		return "redirect:/";
	}

	@RequestMapping("/edit/{id}")
	public ModelAndView showEditProductForm(@PathVariable(name = "id") Long id) {
		ModelAndView modelAndView = new ModelAndView("edit_product");
		Product product = service.get(id);
		modelAndView.addObject("product", product);

		return modelAndView;
	}

	@RequestMapping("/delete/{id}")
	public String deleteProduct(@PathVariable(name = "id") Long id) {
		service.delete(id);

		return "redirect:/";
	}

}

index.html







Product Manager



	

Product Manager

Create New Product

Filter:    
 
Product ID Name Brand Made In Price Actions
Product ID Name Brand Made in Price Edit     Delete
   
Total items: [[${totalItems}]] - Page [[${currentPage}]] of [[${totalPages}]]     First First    Previous Previous    [[${i}]]     [[${i}]]     Next Next    Last Last   

new_product.html





Create new product


	

Create new product


Product Name:
Brand
Made in:
Price:

edit_product.html





Edit product


	

Edit product


Product ID:
Product Name:
Brand
Made in:
Price:

下载:

GitHub - allwaysoft/ProductManager_Sorting_Paging_Search_Filter: Product Manager CRUD Application with Spring Boot, Spring MVC, Spring Data JPA with Hibernate, ThymeLeaf, MySQL. With Sorting, Paging, Searching and Filtering.

你可能感兴趣的:(java,spring,boot,spring)