SpringBoot2.x使用Jpa实现CURD(增删改查)

介绍:
SpringBoot2.x使用Jpa实现CURD(增删改查)

说明:
目录结构如下:
SpringBoot2.x使用Jpa实现CURD(增删改查)_第1张图片
po映射数据库表,
Repository提供数据库交流,
Service定义接口,impl实现接口,controller处理请求
一、Po层Student

package com.curd.curdtojpa.po;

import javax.persistence.*;
import java.util.Date;


@Entity
@Table(name="t_student")
public class Student {

    @Id
    @GeneratedValue
    private Long id;
    private String cardId;
    private String name;
    private String age;
    private String sex;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getCardId() {
        return cardId;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", CardId='" + cardId + '\'' +
                ", name='" + name + '\'' +
                ", age='" + age + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }
}

二、Dao层StudentRepository

package com.curd.curdtojpa.dao;

import com.curd.curdtojpa.po.Student;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;

//数据访问接口,与数据库打交道
public interface StudentRepository extends JpaRepository<Student,Long> {

    Student findByCardId(String CardId);

    @Query("select s from Student s where s.cardId like ?1 or s.name like ?1")
    Page<Student> findByQuery(String query, Pageable pageable);
}

三、Service层,StudentService,StudentServiceImpl
StudentService

package com.curd.curdtojpa.service;

import com.curd.curdtojpa.po.Student;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import javax.management.Query;
import java.util.List;

//Service层接收调用,调用dao,服务controller
//StudentService定义了一系列接口,StudentServiceImpl实现接口
public interface StudentService {

    Student saveStudent(Student student);//保存数据

    Student updateStudent(Long id,Student student);//更新数据

    Student getStudent(Long id);//通过id获得该条数据

    Student getStudentByCardId(String CardId);//通过CardId获得该条数据

    void deleteStudent(Long id);//根据id删除数据

    Page<Student> listStudent(Pageable pageable);//分页

    Page<Student> listStudent(String query,Pageable pageable);//查询,查询的界面也有分页

    List<Student> listStudent();//数据显示

}


StudentServiceImpl

package com.curd.curdtojpa.service;

import com.curd.curdtojpa.dao.StudentRepository;
import com.curd.curdtojpa.po.Student;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.persistence.Temporal;
import java.util.List;

//Impl实现service接口
@Service
public class StudentServiceImpl implements StudentService{

    @Autowired
    private StudentRepository studentRepository;

    @Transactional
    @Override
    public Student saveStudent(Student student) {
        return studentRepository.save(student);//保存
    }

    @Transactional
    @Override
    public Student updateStudent(Long id, Student student) {
        Student s=studentRepository.findById(id).orElse(null);//找到对应记录
        if(s==null){System.out.println("该学生不存在记录中!");}
        BeanUtils.copyProperties(student,s);//student->s
        return studentRepository.save(s);
    }

    @Override
    public Student getStudent(Long id) {
        return studentRepository.findById(id).orElse(null);
    }

    @Override
    public Student getStudentByCardId(String CardId) {
        return studentRepository.findByCardId(CardId);
    }

    @Transactional
    @Override
    public void deleteStudent(Long id) {
        studentRepository.deleteById(id);
    }

    @Override
    public Page<Student> listStudent(Pageable pageable) {
        return studentRepository.findAll(pageable);//所有数据都分页
    }

    @Override
    public Page<Student> listStudent(String query, Pageable pageable) {
        return studentRepository.findByQuery(query,pageable);//query:关键字,查询
    }

    @Transactional
    @Override
    public List<Student> listStudent() {
        return studentRepository.findAll();//所有数据
    }
}

四、Controller层StudentController

package com.curd.curdtojpa.controller;

import com.curd.curdtojpa.po.Student;
import com.curd.curdtojpa.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @GetMapping("/student")
    public String StudentList(@PageableDefault(size=5,sort={"id"},
            direction = Sort.Direction.DESC) Pageable pageable,
                              Model model)
    {
        model.addAttribute("page",studentService.listStudent(pageable));
        return "/student";
    }

    @GetMapping("/student/input")
    public String inputStudent(Model model)
    {
        model.addAttribute("student",new Student());
        return "/student-input";
    }

    @PostMapping("/student")
    public String postStudent(@Valid Student student,
                              BindingResult result,
                              RedirectAttributes attributes)
    {
        Student student1=studentService.getStudentByCardId(student.getCardId());
        if(student1!=null)
        {
            result.rejectValue("name","nameError","不能添加重复的Student");
        }
        if(result.hasErrors())
        {
            return "/student-input";
        }
        Student s=studentService.saveStudent(student);
        if(s==null)
        {
            attributes.addFlashAttribute("message","新增失败");
        }else {
            attributes.addFlashAttribute("message","新增成功");
        }
        return "redirect:/student";
    }

    @GetMapping("/student/{id}/input")
    public String editInputStudent(@PathVariable Long id,
                              Model model,
                              RedirectAttributes attributes)
    {
        model.addAttribute("student",studentService.getStudent(id));
        return "/student-input";
    }

    @PostMapping("/student/{id}")
    public String editPostStudent(@PathVariable Long id,
                                  @Valid Student student,
                                  BindingResult result,
                                  RedirectAttributes attributes)
    {
        Student student1=studentService.getStudent(id);
        if(result.hasErrors()){
            return "student-input";
        }
        Student s=studentService.updateStudent(id,student);
        if(s==null)
        {
            attributes.addFlashAttribute("message", "更新失败");
        } else {
            attributes.addFlashAttribute("message", "更新成功");
        }
        return "redirect:/student";
    }

    @PostMapping("/search")
    public String searchStudent(@PageableDefault(size = 5,sort = {"id"},
    direction = Sort.Direction.DESC)Pageable pageable,
                                @RequestParam String query,
                                Model model)
    {
        model.addAttribute("page",studentService.listStudent("%"+query+"%",pageable));
        model.addAttribute("query",query);
        return "/search";
    }

    @GetMapping("/student/{id}/delete")
    public String deleteStudent(@PathVariable Long id,
                                RedirectAttributes attributes)
    {
        studentService.deleteStudent(id);
        attributes.addFlashAttribute("nessage","删除成功");
        return "redirect:/student";
   }

}

student页面


<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head >
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Studenttitle>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
    <link rel="stylesheet" href="../static/css/me.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
    <link rel="stylesheet" href="../static/css/typo.css"          th:href="@{/css/typo.css}"          >
    <link rel="stylesheet" href="../static/css/animate.css"       th:href="@{/css/animate.css}"       >
    <link rel="stylesheet" href="../static/lib/prism/prism.css"   th:href="@{/lib/prism/prism.css}"   >
    <link rel="stylesheet" href="../static/lib/tocbot/tocbot.css" th:href="@{/lib/tocbot/tocbot.css}" >
    <link rel="stylesheet" href="../static/css/me.css"            th:href="@{/css/me.css}"            >
    <link rel="shortcut icon" href="https://cdn.luogu.com.cn/upload/image_hosting/6p87ddu1.png" type="image/x-icon" />

head>
<body>

<nav class="ui inverted attached segment m-padded-tb-mini m-shadow-small" >
    <div class="ui container">
        <div class="ui inverted secondary stackable menu">
            <h2 class="ui teal header item">管理后台h2>
            <a href="#" class="active m-item item m-mobile-hide"><i class="mini home icon">i>博客a>
            <a href="#" class=" m-item item m-mobile-hide"><i class="mini idea icon">i>分类a>
            <a href="#" class="m-item item m-mobile-hide"><i class="mini tags icon">i>标签a>
            <div class="right m-item item m-mobile-hide">
                <form name="search" action="#" th:action="@{/search}" method="post" target="_blank">
                    <div class="ui icon inverted transparent input m-margin-tb-tiny">
                        <input type="text" name="query" placeholder="Search...." th:value="${query}">
                        <button onclick="document.forms['search'].submit()" class="search link icon">button>
                    div>
                form>

            div>

            <div class="right m-item m-mobile-hide menu">
                <div class="ui dropdown  item">
                    <div class="text">
                        <img class="ui avatar image" src="https://unsplash.it/100/100?image=1005">
                        yxll
                    div>
                    <i class="dropdown icon">i>
                    <div class="menu">
                        <a href="#" class="item">注销a>
                    div>
                div>
            div>
        div>
    div>
    <a href="#" class="ui menu toggle black icon button m-right-top m-mobile-show">
        <i class="sidebar icon">i>
    a>
nav>
<div class="ui attached pointing menu">
    <div class="ui container">
        <div class="right menu">
            <a href="#" th:href="@{/student/input}" class="item">新增a>
            <a href="#" th:href="@{/student}" class="teal active item">列表a>
        div>
    div>
div>


<div  class="m-container-small m-padded-tb-big">
    <div class="ui container">
        <div class="ui success message" th:unless="${#strings.isEmpty(message)}">
            <i class="close icon">i>
            <div class="header">提示:div>
            <p th:text="${message}">恭喜,操作成功!p>
        div>
        <table class="ui celled table">
            <thead>
            <tr>
                <th>th>
                <th>身份证号th>
                <th>学生姓名th>
                <th>学生年龄th>
                <th>学生性别th>
                <th>操作th>
            tr>
            thead>
            <tbody>
            <tr th:each="students,iterStat : ${page.content}">
                <td th:text="${iterStat.count}">学生编号td>
                <td th:text="${students.CardId}">身份证号td>
                <td th:text="${students.name}">学生姓名td>
                <td th:text="${students.age}">学生年龄td>
                <td th:text="${students.sex}">学生性别td>
                <td>
                    <a href="#" th:href="@{/student/{id}/input(id=${students.id})}"  class="ui mini teal basic button">编辑a>
                    <a href="#" th:href="@{/student/{id}/delete(id=${students.id})}" class="ui mini red basic button">删除a>
                td>
            tr>
            tbody>
            <tfoot>
            <tr>
                <th colspan="6" >
                    <div class="ui mini pagination menu" th:if="${page.totalPages}>1">
                        <a th:href="@{/student(page=${page.number}-1)}" class=" item" th:unless="${page.first}">上一页a>
                        <a th:href="@{/student(page=${page.number}+1)}" class=" item" th:unless="${page.last}">下一页a>
                    div>
                    <a href="#" th:href="@{/student/input}"  class="ui mini right floated teal basic button">新增a>
                th>
             tr>
             tfoot>
        table>
    div>
div>

<br>
<br>

<footer  class="ui inverted vertical segment m-padded-tb-massive">
    <div class="ui center aligned container">
        <div class="ui inverted divided stackable grid">
            <div class="three wide column">
                <div class="ui inverted link list">
                    <div class="item">
                        <img src="../static/images/wechat.jpg" class="ui rounded image" alt="" style="width: 110px">
                    div>
                div>
            div>
            <div class="three wide column">
                <h4 class="ui inverted header m-text-thin m-text-spaced " >最新博客h4>
                <div class="ui inverted link list">
                    <a href="#" class="item m-text-thin">用户故事(User Story)a>
                    <a href="#" class="item m-text-thin">用户故事(User Story)a>
                    <a href="#" class="item m-text-thin">用户故事(User Story)a>
                div>
            div>
            <div class="three wide column">
                <h4 class="ui inverted header m-text-thin m-text-spaced ">联系我h4>
                <div class="ui inverted link list">
                    <a href="#" class="item m-text-thin">Email:[email protected]a>
                    <a href="#" class="item m-text-thin">QQ:1614639905a>
                div>
            div>
            <div class="seven wide column">
                <h4 class="ui inverted header m-text-thin m-text-spaced ">Blogh4>
                <p class="m-text-thin m-text-spaced m-opacity-mini">这是我的个人博客、会分享关于编程、写作、思考相关的任何内容,希望可以给来到这儿的人有所帮助...p>
            div>
        div>
        <div class="ui inverted section divider">div>
        <p class="m-text-thin m-text-spaced m-opacity-tiny">Copyright © 2019 yxll Designed by yxllp>
    div>

footer>

<script>
    $('.menu.toggle').click(function () {
        $('.m-item').toggleClass('m-mobile-hide');
    });

    $('.ui.dropdown').dropdown({
        on : 'hover'
    });

    //消息提示关闭初始化
    $('.message .close')
        .on('click', function () {
            $(this)
                .closest('.message')
                .transition('fade');
        });
script>
body>
html>

student-input页面


<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>标签新增title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
  <link rel="stylesheet" href="../static/lib/editormd/css/editormd.min.css">
  <link rel="stylesheet" href="../static/css/me.css">
head>
<body>

  
  <nav  class="ui inverted attached segment m-padded-tb-mini m-shadow-small" >
    <div class="ui container">
      <div class="ui inverted secondary stackable menu">
        <h2 class="ui teal header item">管理后台h2>
        <a href="#" class="active m-item item m-mobile-hide"><i class="mini home icon">i>博客a>
        <a href="#" class=" m-item item m-mobile-hide"><i class="mini idea icon">i>分类a>
        <a href="#" class="m-item item m-mobile-hide"><i class="mini tags icon">i>标签a>
        <div class="right m-item m-mobile-hide menu">
          <div class="ui dropdown  item">
            <div class="text">
              <img class="ui avatar image" src="https://unsplash.it/100/100?image=1005">
              yxll
            div>
            <i class="dropdown icon">i>
            <div class="menu">
              <a href="#" class="item">注销a>
            div>
          div>
        div>
      div>
    div>
    <a href="#" class="ui menu toggle black icon button m-right-top m-mobile-show">
      <i class="sidebar icon">i>
    a>
  nav>
  <div class="ui attached pointing menu">
    <div class="ui container">
      <div class="right menu">
        <a href="#" th:href="@{/student/input}" class="active item">新增a>
        <a href="#" th:href="@{/student}" class="teal  item">列表a>
      div>
    div>
  div>

  
  <div  class="m-container-small m-padded-tb-big">
    <div class="ui container">
      <form action="#" method="post"  th:object="${student}" th:action="*{id}==null ? @{/student} : @{/student/{id}(id=*{id})} "  class="ui form">
        <input type="hidden" name="id" th:value="*{id}">
        <div class=" field">
          <div class="ui left labeled input">
            <label class="ui teal basic label">身份证号label><p>p>
            <input type="text" name="CardId" placeholder="身份证号" th:value="*{CardId}" >
          div>
          <div class="ui left labeled input">
            <label class="ui teal basic label">学生姓名label>
            <input type="text" name="name" placeholder="学生姓名" th:value="*{name}" >
          div>
          <div class="ui left labeled input">
            <label class="ui teal basic label">学生年龄label>
            <input type="text" name="age" placeholder="学生年龄" th:value="*{age}" >
          div>
          <div class="ui left labeled input">
            <label class="ui teal basic label">学生性别label>
            <input type="text" name="sex" placeholder="学生性别" th:value="*{sex}" >
          div>

        div>

        <div class="ui error message">div>
        
        <div class="ui right aligned container">
          <button type="button" class="ui button" onclick="window.history.go(-1)" >返回button>
          <button class="ui teal submit button">提交button>
        div>

      form>
    div>
  div>

  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  <br>
  
  <footer  class="ui inverted vertical segment m-padded-tb-massive">
    <div class="ui center aligned container">
      <div class="ui inverted divided stackable grid">
        <div class="three wide column">
          <div class="ui inverted link list">
            <div class="item">
              <img src="../../static/images/wechat.jpg" class="ui rounded image" alt="" style="width: 110px">
            div>
          div>
        div>
        <div class="three wide column">
          <h4 class="ui inverted header m-text-thin m-text-spaced " >最新博客h4>
          <div class="ui inverted link list">
            <a href="#" class="item m-text-thin">用户故事(User Story)a>
            <a href="#" class="item m-text-thin">用户故事(User Story)a>
            <a href="#" class="item m-text-thin">用户故事(User Story)a>
          div>
        div>
        <div class="three wide column">
          <h4 class="ui inverted header m-text-thin m-text-spaced ">联系我h4>
          <div class="ui inverted link list">
            <a href="#" class="item m-text-thin">Email:[email protected]a>
            <a href="#" class="item m-text-thin">QQ:1614639905a>
          div>
        div>
        <div class="seven wide column">
          <h4 class="ui inverted header m-text-thin m-text-spaced ">Blogh4>
          <p class="m-text-thin m-text-spaced m-opacity-mini">这是我的个人博客、会分享关于编程、写作、思考相关的任何内容,希望可以给来到这儿的人有所帮助...p>
        div>
      div>
      <div class="ui inverted section divider">div>
      <p class="m-text-thin m-text-spaced m-opacity-tiny">Copyright © 2019 yxll Designed by yxllp>
    div>

  footer>


  <script>

    $('.menu.toggle').click(function () {
      $('.m-item').toggleClass('m-mobile-hide');
    });

    $('.ui.dropdown').dropdown({
      on : 'hover'
    });

    $('.ui.form').form({
      fields : {
        title : {
          identifier: 'name',
          rules: [{
            type : 'empty',
            prompt: '请输入标签名称'
          }]
        }
      }
    });

  script>
body>
html>

search页面


<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head >
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>标签管理title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
  <link rel="stylesheet" href="../static/css/me.css">
head>
<body>


<nav class="ui inverted attached segment m-padded-tb-mini m-shadow-small" >
  <div class="ui container">
    <div class="ui inverted secondary stackable menu">
      <h2 class="ui teal header item">管理后台h2>
      <a href="#" class="active m-item item m-mobile-hide"><i class="mini home icon">i>博客a>
      <a href="#" class=" m-item item m-mobile-hide"><i class="mini idea icon">i>分类a>
      <a href="#" class="m-item item m-mobile-hide"><i class="mini tags icon">i>标签a>
      <div class="right m-item item m-mobile-hide">

        <form name="search" action="#" th:action="@{/search}" method="post" target="_blank">
          <div class="ui icon inverted transparent input m-margin-tb-tiny">
            <input type="text" name="query" placeholder="Search...." th:value="${query}">
            <button onclick="document.forms['search'].submit()" class="search link icon">button>
          div>
        form>

      div>

      <div class="right m-item m-mobile-hide menu">
        <div class="ui dropdown  item">
          <div class="text">
            <img class="ui avatar image" src="https://unsplash.it/100/100?image=1005">
            yxll
          div>
          <i class="dropdown icon">i>
          <div class="menu">
            <a href="#" class="item">注销a>
          div>
        div>
      div>
    div>
  div>
  <a href="#" class="ui menu toggle black icon button m-right-top m-mobile-show">
    <i class="sidebar icon">i>
  a>
nav>



<div  class="m-container-small m-padded-tb-big">
  <div class="ui container">
    <table class="ui celled table">
      <thead>
      <tr>
        <th>th>
        <th>名称th>

      tr>
      thead>
      <tbody>
      <tr th:each="students,iterStat : ${page.content}">
        <td th:text="${iterStat.count}">类型顺序td>
        <td th:text="${students.name}">类型名称td>
      tr>
      tbody>
    table>
  div>
div>

<br>
<br>

<footer  class="ui inverted vertical segment m-padded-tb-massive">
  <div class="ui center aligned container">
    <div class="ui inverted divided stackable grid">
      <div class="three wide column">
        <div class="ui inverted link list">
          <div class="item">
            <img src="../static/images/wechat.jpg" class="ui rounded image" alt="" style="width: 110px">
          div>
        div>
      div>
      <div class="three wide column">
        <h4 class="ui inverted header m-text-thin m-text-spaced " >最新博客h4>
        <div class="ui inverted link list">
          <a href="#" class="item m-text-thin">用户故事(User Story)a>
          <a href="#" class="item m-text-thin">用户故事(User Story)a>
          <a href="#" class="item m-text-thin">用户故事(User Story)a>
        div>
      div>
      <div class="three wide column">
        <h4 class="ui inverted header m-text-thin m-text-spaced ">联系我h4>
        <div class="ui inverted link list">
          <a href="#" class="item m-text-thin">Email:[email protected]a>
          <a href="#" class="item m-text-thin">QQ:1614639905a>
        div>
      div>
      <div class="seven wide column">
        <h4 class="ui inverted header m-text-thin m-text-spaced ">Blogh4>
        <p class="m-text-thin m-text-spaced m-opacity-mini">这是我的个人博客、会分享关于编程、写作、思考相关的任何内容,希望可以给来到这儿的人有所帮助...p>
      div>
    div>
    <div class="ui inverted section divider">div>
    <p class="m-text-thin m-text-spaced m-opacity-tiny">Copyright © 2019 yxll Designed by yxllp>
  div>

footer>

<script>
  $('.menu.toggle').click(function () {
    $('.m-item').toggleClass('m-mobile-hide');
  });

  $('.ui.dropdown').dropdown({
    on : 'hover'
  });

  //消息提示关闭初始化
  $('.message .close')
          .on('click', function () {
            $(this)
                    .closest('.message')
                    .transition('fade');
          });
script>
body>
html>

源码:https://gitee.com/yuexiliuli/SpringBoot2.x_CURD_To_Jpa/

你可能感兴趣的:(Springboot)