IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> springboot+springdata jpa+thymeleaf项目实战 -> 正文阅读

[Java知识库]springboot+springdata jpa+thymeleaf项目实战

前几天把java实训项目写好了,项目使用的是springboot+spring data jpa+thymeleaf。

对于我这个后端的孩子来说,写前端页面太折磨了。

这个是我们的项目要求,还是很简单的:

?

下面是properties文件的配置

spring.application.name=teacher
# 应用服务 WEB 访问端口
server.port=8080
# THYMELEAF (ThymeleafAutoConfiguration)
# 开启模板缓存(默认值: true )
spring.thymeleaf.cache=false
# 检查模板是否存在,然后再呈现
spring.thymeleaf.check-template=true
# 检查模板位置是否正确(默认值 :true )
spring.thymeleaf.check-template-location=true
#Content-Type 的值(默认值: text/html )
spring.thymeleaf.content-type=text/html
# 开启 MVC Thymeleaf 视图解析(默认值: true )
spring.thymeleaf.enabled=true
# 模板编码
spring.thymeleaf.encoding=UTF-8
# 要被排除在解析之外的视图名称列表,?逗号分隔
spring.thymeleaf.excluded-view-names=
# 要运?于模板之上的模板模式。另? StandardTemplate-ModeHandlers( 默认值: HTML5)
spring.thymeleaf.mode=HTML5
# 在构建 URL 时添加到视图名称前的前缀(默认值: classpath:/templates/ )
spring.thymeleaf.prefix=classpath:/templates/
# 在构建 URL 时添加到视图名称后的后缀(默认值: .html )
spring.thymeleaf.suffix=.html
spring.datasource.url=jdbc:mysql://localhost:3306/teachers?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=12345678


mybatis.mapper-locations:classpath:mapper/*Dao.xml
mybatis.type-aliases-package=com.teacher.pojo
mybatis.configuration.map-underscore-to-camel-case=true

#自动生成数据库表(关键)
spring.jpa.hibernate.ddl-auto=update
#mysql数据库驱动程序(重要)
#jpa配置:在控制台显示Hibernate的sql(可选)
spring.jpa.show-sql = true

pagehelper.helperDialect=mysql
pagehelper.reasonable=true
pagehelper.supportMethodsArguments=true
pagehelper.params=count=countSql

这个是controller层

package com.teacher.controller;

import com.teacher.pojo.Teacher;
import com.teacher.service.TeacherService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/teacher")
public class TeacherController {

    @Resource
    private TeacherService teacherService;

    /**
     * 增加老师
     */
    @RequestMapping("/addTeacher")
    public String addTeacher(String code,String name,String sex,String major,String education,String school,String faculty,String academic,int data){
        Teacher teacher=new Teacher(code,name,sex,major,education,school,faculty,academic,data);
        teacherService.insertTeacher(teacher);
       // ModelAndView mv=new ModelAndView("teacher-main");
        return "redirect:/teacher/pageTest";
    }

    /**
     * 删除老师
     */
    @RequestMapping("/deleteTeacher/{id}")
    public String deleteUser(@PathVariable int id){
        teacherService.deleteTeacher(id);
        return "redirect:/teacher/findAll";
    }

    //查出原来的数据
    @GetMapping("/modify/{id}")
    public String goUpdate(@PathVariable("id")int id, Model model){
        Teacher teacher=teacherService.findTeacherById(id);
        model.addAttribute("modify",teacher);
        return "modify";
    }

    /**
     * 修改老师
     */
    @RequestMapping("/updateTeacher")
    public String updateTeacher(Teacher teacher){
        teacherService.updateTeacher(teacher);
        return "redirect:/teacher/pageTest";
    }

    /**
     * 查询所有老师
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll(){
        ModelAndView mv=new ModelAndView();
        mv.addObject("newText","你好,Thymeleaf!");
        mv.addObject("gender","1");
        List<Teacher>teacherList= teacherService.findAllTeacher();
        mv.addObject("teacherList",teacherList);
        mv.setViewName("teacher-main");
        return mv;
    }

    /**
     * 通过id查询老师
     */
    @RequestMapping("/findTeacherById/{id}")
    public ModelAndView findByIdyId(@PathVariable int id){
        ModelAndView mv=new ModelAndView();
        mv.addObject("teacherList",teacherService.findTeacherById(id));
        mv.setViewName("findOne");
        return mv;
    }

    /**
     * 根据条件模糊查询教师
     */
    @RequestMapping("/queryByRe")
    public ModelAndView findByIdy(String thing,String type){
        ModelAndView mv=new ModelAndView();
        mv.addObject("teacherList",teacherService.findTeacherByRequire(thing,type));
        System.out.println(teacherService.findTeacherByRequire(thing,type));
        mv.setViewName("require");
        return mv;
    }

    /**
     * 分页查询
     */
    @RequestMapping("/pageTest")
    public ModelAndView find(@RequestParam(value = "pages",defaultValue = "1") int pages){
        ModelAndView mv=new ModelAndView();
        if(pages>0) {
            Map<String, List> map = teacherService.queryTeaByPage(pages);
            List<Integer> list = map.get("总共的页数");
            int totalPages = list.get(0);
            List<Integer> list1 = map.get("总条数");
            int count = list1.get(0);
            List<Teacher> teacherList = map.get("查询信息");
            mv.addObject("teacherList", teacherList);
            mv.addObject("totalPages", totalPages);
            mv.addObject("count", count);
            mv.addObject("pages", pages);
            mv.setViewName("teacher-main");
            return mv;
        }else{
            return null;
        }
    }

    /**
     * 分页缓存
     */
    @RequestMapping("/page")
    public String find1(@RequestParam(value = "pages")int pages){
        if(pages<=0){
            return "redirect:/teacher/pageTest?pages=1";
        }else{
            return "redirect:/teacher/pageTest?pages="+pages;
        }
    }

    /**
     * 分页缓存下一页
     */
    @RequestMapping("/page1")
    public String find2(@RequestParam(value = "pages")int pages){
        Map<String, List> map = teacherService.queryTeaByPage(pages);
        List<Integer> list = map.get("总共的页数");
        int totalPages = list.get(0);
        if(pages>totalPages){
            return "redirect:/teacher/pageTest?pages="+totalPages;
        }else{
            return "redirect:/teacher/pageTest?pages="+pages;
        }
    }

    /**
     * 模糊查询
     */
    @RequestMapping("/queryConcat")
    public ModelAndView findByIdy1(String thing){
        ModelAndView mv=new ModelAndView();
        mv.addObject("teacherList",teacherService.queryConcat(thing));
        mv.setViewName("require");
        return mv;
    }
}

主要的也就是在controller层了,与thymeleaf的结合。

thymeleaf实现分页,之前我在网上也找了相关教程,但是不知道咋回事都没什么效果,于是我就使用limit自己写了一个分页。

在controller层中的代码(上面代码中也有)

/**
     * 分页查询
     */
    @RequestMapping("/pageTest")
    public ModelAndView find(@RequestParam(value = "pages",defaultValue = "1") int pages){
        ModelAndView mv=new ModelAndView();
        if(pages>0) {
            Map<String, List> map = teacherService.queryTeaByPage(pages);
            List<Integer> list = map.get("总共的页数");
            int totalPages = list.get(0);
            List<Integer> list1 = map.get("总条数");
            int count = list1.get(0);
            List<Teacher> teacherList = map.get("查询信息");
            mv.addObject("teacherList", teacherList);
            mv.addObject("totalPages", totalPages);
            mv.addObject("count", count);
            mv.addObject("pages", pages);
            mv.setViewName("teacher-main");
            return mv;
        }else{
            return null;
        }
    }

    /**
     * 分页缓存
     */
    @RequestMapping("/page")
    public String find1(@RequestParam(value = "pages")int pages){
        if(pages<=0){
            return "redirect:/teacher/pageTest?pages=1";
        }else{
            return "redirect:/teacher/pageTest?pages="+pages;
        }
    }

    /**
     * 分页缓存下一页
     */
    @RequestMapping("/page1")
    public String find2(@RequestParam(value = "pages")int pages){
        Map<String, List> map = teacherService.queryTeaByPage(pages);
        List<Integer> list = map.get("总共的页数");
        int totalPages = list.get(0);
        if(pages>totalPages){
            return "redirect:/teacher/pageTest?pages="+totalPages;
        }else{
            return "redirect:/teacher/pageTest?pages="+pages;
        }
    }

?下面的两个缓存主要是为了应对用户点击上一页时避免进入空白页面而写的。

前端代码:

<table>
                                <thead>
                                <tr>
                                    <th>序号</th>
                                    <th>工号</th>
                                    <th>名字</th>
                                    <th>性别</th>
                                    <th>专业</th>
                                    <th>学历</th>
                                    <th>毕业院校</th>
                                    <th>所在院系</th>
                                    <th>职称</th>
                                    <th>参加工作日期</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr th:each="t:${teacherList}">
                                    <td th:text="${t.id}">id</td>
                                    <td th:text="${t.teaCode}">code</td>
                                    <td th:text="${t.teaName}">name</td>
                                    <td th:text="${t.teaSex}">sex</td>
                                    <td th:text="${t.teaMajor}">major</td>
                                    <td th:text="${t.teaEducation}">education</td>
                                    <td th:text="${t.teaSchool}">school</td>
                                    <td th:text="${t.teaFaculty}">faculty</td>
                                    <td th:text="${t.teaAcademic}">academic</td>
                                    <td th:text="${t.teaData}">data</td>
                                    <td><a th:href="@{'/teacher/modify/'+${t.id}}">修改</a> <a th:href="@{'/teacher/deleteTeacher/'+${t.id}}">删除</a> </td>
                                </tr>
                                </tbody>
                            </table>
                            <p>当前为第<span th:text="${pages}"></span>页,总 <span th:text="${totalPages}"></span> 页,共 <span th:text="${count}"></span> 条记录</p>
                            <a th:href="@{/teacher/pageTest(pages=1)}">首页</a>
                            <a th:href="@{/teacher/page(pages=${pages}-1)}">上一页</a>
                            <a th:href="@{/teacher/page1(pages=${pages}+1)}">下一页</a>
                            <a th:href="@{/teacher/pageTest(pages=${totalPages})}">尾页</a>

?

这个是呈现效果。

下面的是service层:

package com.teacher.service;

import com.teacher.pojo.Teacher;
import java.util.List;
import java.util.Map;
public interface TeacherService {
    /**
     * 增加老师
     */
    Teacher insertTeacher(Teacher teacher);

    /**
     * 删除老师
     */
    void deleteTeacher(int id);

    /**
     * 修改老师
     */
    Teacher updateTeacher(Teacher teacher);

    /**
     * 查询所有老师
     */
    List<Teacher> findAllTeacher();

    /**
     * 通过id查询老师
     */
    Teacher findTeacherById(int id);

    /**
     * 根据条件模糊查询教师
     */
    List<Teacher> findTeacherByRequire(String thing,String type);

    /**
     *分页查询全部教师
     */
    Map queryTeaByPage(int pages);

    /**
     * 模糊查询申请表数量
     */
    List<Teacher> queryConcat(String thing);
}




package com.teacher.service.impl;

import com.teacher.pojo.Teacher;
import com.teacher.repository.TeacherRepository;
import com.teacher.service.TeacherService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Resource
    private TeacherRepository teacherRepository;

    @Override
    public Teacher insertTeacher(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    @Override
    public void deleteTeacher(int id) {
        teacherRepository.deleteById(id);
    }

    @Override
    public Teacher updateTeacher(Teacher teacher) {
        return teacherRepository.save(teacher);
    }

    @Override
    public List<Teacher> findAllTeacher() {
        return teacherRepository.findAll();
    }

    @Override
    public Teacher findTeacherById(int id) {
        return teacherRepository.findById(id).orElse(null);
    }

    @Override
    public List<Teacher> findTeacherByRequire(String thing,String type) {
        if(type.equals("teaName")){
            return teacherRepository.queryTeaByName(thing);
        }
        if(type.equals("teaSex")){
            return teacherRepository.queryTeaBySex(thing);
        }
        if(type.equals("teaMajor")){
            return teacherRepository.queryTeaByMajor(thing);
        }
        if(type.equals("teaEducation")){
            return teacherRepository.queryTeaByEdu(thing);
        }
        if(type.equals("teaAcademic")){
            return teacherRepository.queryTeaByAcademic(thing);
        }
        if(type.equals("teaSchool")){
            return teacherRepository.queryTeaBySchool(thing);
        }
        if(type.equals("teaFaculty")){
            return teacherRepository.queryTeaByFaculty(thing);
        }else{
            return null;
        }
    }

    @Override
    public Map queryTeaByPage(int pages) {
        Map<String,List> map=new HashMap<>();
        int num=5,totalPages,total;
        int count=teacherRepository.queryTeaByPageCount();
        if (count % num == 0) {
            totalPages = count / num;
        } else {
            total = count / num;
            totalPages = total + 1;
        }
        List<Integer> list = new LinkedList<>();
        list.add(totalPages);
        map.put("总共的页数", list);
        List<Integer> list1 = new LinkedList<>();
        list1.add(count);
        map.put("总条数", list1);
        int thePage = (pages - 1) * num;
        List<Teacher> list2 = teacherRepository.queryTeaByPage( thePage, num);
        map.put("查询信息", list2);
        return map;
    }

    @Override
    public List<Teacher> queryConcat(String thing) {
        return teacherRepository.queryConcat(thing);
    }
}

当然,尽量把逻辑层写在service层。

?下面的是repository层:

package com.teacher.repository;

import com.teacher.pojo.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.List;

public interface TeacherRepository extends JpaRepository<Teacher, Integer>, JpaSpecificationExecutor {
    @Query(value="select * from teacher where id=?",nativeQuery = true)
    Teacher queryTeaByID(int id);

    /**
     *根据姓名模糊查询
     */
    @Query(value="select * from teacher where tea_name like %?%",nativeQuery = true)
    List<Teacher> queryTeaByName(String teaName);

    /**
     *根据性别模糊查询
     */
    @Query(value="select * from teacher where tea_sex like %?%",nativeQuery = true)
    List<Teacher> queryTeaBySex(String teaSex);

    /**
     *根据专业模糊查询
     */
    @Query(value="select * from teacher where tea_major like %?%",nativeQuery = true)
    List<Teacher> queryTeaByMajor(String teaMajor);

    /**
     *根据学历模糊查询
     */
    @Query(value="select * from teacher where tea_education like %?%",nativeQuery = true)
    List<Teacher> queryTeaByEdu(String teaEducation);

    /**
     *根据职称模糊查询
     */
    @Query(value="select * from teacher where tea_academic like %?%",nativeQuery = true)
    List<Teacher> queryTeaByAcademic(String teaAcademic);

    /**
     *根据毕业院校模糊查询
     */
    @Query(value="select * from teacher where tea_school like %?%",nativeQuery = true)
    List<Teacher> queryTeaBySchool(String teaSchool);

    /**
     *根据所在院系模糊查询
     */
    @Query(value="select * from teacher where tea_faculty like %?%",nativeQuery = true)
    List<Teacher> queryTeaByFaculty(String teaFaculty);

    /**
     *分页查询全部教师
     */
    @Query(value="select * from teacher limit ?1,?2",nativeQuery = true)
    List<Teacher> queryTeaByPage(int pages,int num);

    /**
     *分页查询全部教师数量
     */
    @Query(value="select count(*) from teacher",nativeQuery = true)
    int queryTeaByPageCount();

    /**
     * 模糊查询申请表数量
     */
    @Query(value = "select * from teacher where concat(tea_name,tea_sex,tea_major,tea_education,tea_academic,tea_school,tea_faculty) like concat('%',?1,'%')", nativeQuery = true)
    List<Teacher> queryConcat(@Param("thing") String thing);
}

下面的是实体类:

package com.teacher.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.jpa.domain.support.AuditingEntityListener;
import javax.persistence.*;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name="teacher")
@EntityListeners(AuditingEntityListener.class)
public class Teacher{
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    @Column(name = "tea_code")
    private String teaCode;
    @Column(name = "tea_name")
    private String teaName;
    @Column(name = "tea_sex")
    private String teaSex;
    @Column(name = "tea_major")
    private String teaMajor;
    @Column(name = "tea_education")
    private String teaEducation;
    @Column(name = "tea_school")
    private String teaSchool;
    @Column(name = "tea_faculty")
    private String teaFaculty;
    @Column(name = "tea_academic")
    private String teaAcademic;
    @Column(name = "tea_data")
    private int teaData;

    public Teacher(String teaCode, String teaName, String teaSex, String teaMajor, String teaEducation, String teaSchool, String teaFaculty, String teaAcademic, int teaData) {
        this.teaCode = teaCode;
        this.teaName = teaName;
        this.teaSex = teaSex;
        this.teaMajor = teaMajor;
        this.teaEducation = teaEducation;
        this.teaSchool = teaSchool;
        this.teaFaculty = teaFaculty;
        this.teaAcademic = teaAcademic;
        this.teaData = teaData;
    }
}

?下面是pom文件在项目建成后加的依赖:

<!--spring-data-jpa-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
            <scope>runtime</scope>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>

下面的是我的页面展示效果(页面比较丑,大家做好心理准备):

下面的是主页

?

这个是录入教师

?

这个是教师查询:

?

下面的是我的查询后跳转的页面(为了偷懒,没有写分页):

?

这个是修改页面:

?

?原本我想要的效果是局部更新,但是经询问前端孩子之后,我决定放弃局部更新转为多写几个页面。

近日总结:

最近其实大部分时间是比较闲一点的,我们的项目我负责的接口已经写完了,这几天也是写一些零零散散的前端需要的接口,特别是实训项目完成后,闲的感觉更甚。

对于未来一段时间,我打算考驾照,先把科目一和科目二过了,其他的看时间安排,还有就是学英语,复习java基础知识,每天一道剑指offer。

?

?

?

?

?

?

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-07-20 18:38:23  更:2022-07-20 18:39:07 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2025年1日历 -2025/1/31 7:08:24-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码