springData增删改查+分页+模糊

demo的结构:

springData增删改查+分页+模糊_第1张图片

配置文件:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
    username: root
    password: root
  jpa:
    show-sql: true  #显示sql语句
    hibernate:
      ddl-auto: update
      naming:
        implicit-strategy: org.hibernate.boot.model.naming.ImplicitNamingStrategyComponentPathImpl
        physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
    database: mysql #配置现在所使用的数据库

pom文件:

<dependencies>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-data-jpaartifactId>
    dependency>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-thymeleafartifactId>
    dependency>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-webartifactId>
    dependency>
    
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-devtoolsartifactId>
        <scope>runtimescope>
        <optional>trueoptional>
    dependency>
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <scope>runtimescope>
    dependency>
    <dependency>
        <groupId>org.projectlombokgroupId>
        <artifactId>lombokartifactId>
        <optional>trueoptional>
    dependency>
    <dependency>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-testartifactId>
        <scope>testscope>
    dependency>
    <dependency>
        <groupId>org.junit.jupitergroupId>
        <artifactId>junit-jupiter-apiartifactId>
        <version>RELEASEversion>
        <scope>compilescope>
    dependency>
dependencies>

实体类代码:

@Data//生产set get
@Entity//注入到spring容器中
@Table(name = "students")//对应数据库表名
public class Student {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY) //自增长
    private Integer id;
    
    private String name;
    
    private String sex;
}

dao层代码:

@Repository
public interface StudentDao extends JpaRepository<Student,Integer> {

}

实现层代码:

public interface StudentService {
    /**
     * 新增
     * @param student 新增对象
     * @return springData提供的方法是返回的对象,所以我们也需要返回对象
     */
    Student save(Student student);

    /**
     * 修改
     * @param student 修改对象
     * @return springData提供的方法是返回的对象,所以我们也需要返回对象
     */
    Student update(Student student);

    /**
     * 删除
     * @param id 根据id删除
     */
    void delete(Integer id);

    /**
     * 分页
     * @param page 页码
     * @param size 每页数量
     * @param student 用于存储模糊查询参数
     * @return
     */
    Page<Student> findByPage(Integer page, Integer size,Student student);

    /**
     * 通过id 查询
     * @param id 根据id查询,用于修改
     * @return springData提供的方法是返回的对象,所以我们也需要返回对象
     */
    Student findById(Integer id);
}
接口
@Service
public class StudentServiceImpl implements StudentService {

    /**
     * 自动匹配
     */
    @Autowired
    private StudentDao studentDao;

    /**
     * 新增
     * @param student 新增对象
     * @return springData提供的方法是返回的对象,所以我们也需要返回对象
     */
    @Override
    public Student save(Student student) {
        return studentDao.save(student);
    }

    /**
     * 修改
     * @param student 修改对象
     * @return springData提供的方法是返回的对象,所以我们也需要返回对象
     */
    @Override
    public Student update(Student student) {
        return studentDao.save(student);
    }

    /**
     * 删除
     * @param id 根据id删除
     */
    @Override
    public void delete(Integer id) {
        studentDao.deleteById(id);
    }

    /**
     * 分页
     * @param page 页码
     * @param size 每页数量
     * @param student 用于存储模糊查询参数
     * @return
     */
    @Override
    public Page<Student> findByPage(Integer page, Integer size,Student student) {
        //模糊查询,需要注意的是 name要和你所需要查询的字段名相同
        ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("name",ExampleMatcher.GenericPropertyMatchers.startsWith());
        // Example.of(student,matcher);因为第一个参数只能是对象,所以我们需要用对象存储查询条件
        Example<Student> studentExample = Example.of(student,matcher);
        //分页初始化
        PageRequest request = PageRequest.of(page, size);
        //分页查询
        Page<Student> studentPage =studentDao.findAll(studentExample,request);
        return studentPage;
    }

    /**
     * 通过id 查询
     * @param id 根据id查询,用于修改
     * @return springData提供的方法是返回的对象,所以我们也需要返回对象
     */
    @Override
    public Student findById(Integer id) {
        return studentDao.findById(id).get();
    }
}

控制层:

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 页面跳转
     * @return
     */
    @RequestMapping("/add")
    public String add(Student student ,Model model){
        model.addAttribute("student",student);
        return "add";
    }

    /**
     * 新增
     *
     * @param student
     * @return
     */
    @RequestMapping("/save")
    public String save(Student student) {
        studentService.update(student);
        return "redirect:findByPage";
    }

    /**
     * 删除
     *
     * @param id
     */
    @RequestMapping("/delete")
    public String delete(@RequestParam(value = "id",required = false) Integer id,
                         Model model) {
        studentService.delete(id);
        return "redirect:findByPage";
    }

    /**
     * 分页
     * 在服务层我已经表明的很清楚啦,就不再一一解释了
     * @param page
     * @param size
     * @return
     */
    @RequestMapping("/findByPage")
    public String findByPage(@RequestParam(value = "page",required = false) Integer page,
                             @RequestParam(value = "size",required = false) Integer size,
                             Model model,Student student) {
        if (page == null) {
            page = 0; //初始化页码,注意他是从0开始
        }
        if (size == null) {
            size = 2; //初始化每页条数
        }
        Page<Student> byPage = studentService.findByPage(page, size,student);
        model.addAttribute("student", byPage);
        model.addAttribute("name",student.getName());//用于包存查询条件,不然上一页下一页会数据丢失
        return "main";
    }

    /**
     * 通过id 查询
     *
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public String findById(@RequestParam(value = "id",required = false) Integer id,
                           Model model) {
        Student byId = studentService.findById(id);
        model.addAttribute("student",byId);
        return "add";
    }
}

html首页:


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
    <form action="/findByPage" method="post">
        姓名:<input type="text" name="name"/><br />
        <input type="submit" value="查询"/>
    form>
    <table border="1" cellspacing="0" cellpadding="5">
        <tr>
            <th>编号th>
            <th>姓名th>
            <th>性别th>
            <th colspan="2">操作th>
        tr>
        <tr th:each="s:${student}">
            <td th:text="${s.id}">td>
            <td th:text="${s.name}">td>
            <td th:text="${s.sex}">td>
            <td><a th:href="@{/findById(id=${s.id})}">修改a>td>
            <td><a th:href="@{/delete(id=${s.id})}">删除a>td>
        tr>
    table><span th:text="${student.getNumber()+1}">span>页/共<span th:text="${student.getTotalPages()}">span><br/>
    <a th:href="@{/findByPage(page=0,name=${name})}">首页a>
    <span th:if="${student.getNumber()} > 0">
        <a th:href="@{/findByPage(page=${student.getNumber()- 1},name=${name})}">上一页a>
    span>
    <span th:if="${student.getNumber()} < ${student.getTotalPages()-1}">
        <a th:href="@{/findByPage(page=${student.getNumber()+ 1},name=${name})}">下一页a>
    span>
    <a th:href="@{/findByPage(page=${student.getTotalPages()-1},name=${name})}">尾页a>
    <a href="/add">新增a>
body>
html>

增加和修改页面


<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Titletitle>
head>
<body>
<form action="/save" method="post">
    <input type="hidden" name="id" th:value="${student.id}" />
    姓名:<input type="text" name="name" th:value="${student.name}"/>
    性别:<input type="text" name="sex" th:value="${student.sex}"/>
    <input type="submit" value="保存"/>
form>
body>
html>

你可能感兴趣的:(springData)