介紹:
SpringBoot2.x使用Jpa實現CURD(增刪改查)
說明:
目錄結構如下:
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頁面
<!DOCTYPE html>
<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>Student</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">
<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-->
<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:1614639905</a>
</div>
</div>
<div class="seven wide column">
<h4 class="ui inverted header m-text-thin m-text-spaced ">Blog</h4>
<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 yxll</p>
</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頁面
<!DOCTYPE html>
<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 negative message" th:if="${#fields.hasErrors('name')}" >
<i class="close icon"></i>
<div class="header">驗證失敗</div>
<p th:errors="*{name}">提交信息不符合規則</p>
</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-->
<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:1614639905</a>
</div>
</div>
<div class="seven wide column">
<h4 class="ui inverted header m-text-thin m-text-spaced ">Blog</h4>
<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 yxll</p>
</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頁面
<!DOCTYPE html>
<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-->
<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:1614639905</a>
</div>
</div>
<div class="seven wide column">
<h4 class="ui inverted header m-text-thin m-text-spaced ">Blog</h4>
<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 yxll</p>
</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>