Spring Data JPA是更大的Spring Data系列的一部分,可以轻松实现基于JPA的存储库。此模块处理对基于JPA的数据访问层的增强支持。它使构建使用数据访问技术的Spring驱动应用程序变得更加容易。
在相当长的一段时间内,实现应用程序的数据访问层一直很麻烦。必须编写太多样板代码来执行简单查询以及执行分页和审计。Spring Data JPA旨在通过减少实际需要的工作量来显着改善数据访问层的实现。作为开发人员,您编写存储库接口,包括自定义查找器方法,Spring将自动提供实现。
基于Spring和JPA构建存储库的复杂支持
支持Querydsl谓词,从而支持类型安全的JPA查询
透明审核域类
分页支持,动态查询执行,集成自定义数据访问代码的能力
@Query在引导时验证带注释的查询
支持基于XML的实体映射
基于JavaConfig的存储库配置介绍@EnableJpaRepositories。
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/jpademo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
username: root
password: root
jpa:
# 使用什么类型数据库
database: mysql
show-sql: true
hibernate:
ddl-auto: update #执行DDL语句时,是创建create,创建删除create-drop,更新update
naming:
#这个是默认写法,以属性名命名数据库列名
physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
package com.zhaolei.springdatajpa.pojo;
import lombok.Data;
import javax.persistence.*;
/**
* @author 15579
* 2019/6/3 14:09
* 文件说明:Student实体类
*/
@Data
@Table
@Entity //数据库没有此实体类对应的表就会自动生成
public class Student {
@Id
//自动增长
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column
private String name;
@Column
private String sex;
}
Dao层
package com.zhaolei.springdatajpa.dao;
import com.zhaolei.springdatajpa.pojo.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.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* @author 15579
* 2019/6/3 14:21
* 文件说明:StudentDao层
*/
@Repository
public interface StudentDao extends JpaRepository<Student,Integer>, JpaSpecificationExecutor<Student>{
//nativeQuery =true 表示这是原生SQL
@Query(value = "SELECT * from student where `name` like concat('%',?,'%')",nativeQuery = true)
Page<Student> findLikeNameByPage(String name, Pageable pageable);
}
Service层
package com.zhaolei.springdatajpa.Service;
import com.zhaolei.springdatajpa.pojo.Student;
import org.springframework.data.domain.Page;
import java.util.List;
/**
* @author 15579
* 2019/6/3 14:23
* 文件说明:StudentService层
*/
public interface StudentService {
/**
* 查询所有学生信息
* @return
*/
List<Student> findAll();
/**
* 新增学生信息
* @param student
* @return
*/
Student save(Student student);
/**
* 修改
* @param student
* @return
*/
Student update(Student student);
/**
* 删除学生
* @param id
*/
void deleteStu(Integer id);
/**
* 分页查询
* @param pageNum
* @param pageSize
* @return
*/
Page<Student> findByPage(Integer pageNum,Integer pageSize,Student student);
/**
* 根据编号查询
* @param id
* @return
*/
Student findStudentById(Integer id);
}
impl (实现类)
package com.zhaolei.springdatajpa.Service.impl;
import com.sun.deploy.util.StringUtils;
import com.zhaolei.springdatajpa.Service.StudentService;
import com.zhaolei.springdatajpa.dao.StudentDao;
import com.zhaolei.springdatajpa.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import javax.persistence.criteria.*;
import java.util.ArrayList;
import java.util.List;
/**
* @author 15579
* 2019/6/3 14:26
* 文件说明:
*/
@Service
public class StudentServiceImpl implements StudentService {
@Autowired
private StudentDao studentDao;
/**
* 查询所有学生信息
*
* @return
*/
@Override
public List<Student> findAll() {
return studentDao.findAll();
}
/**
* 新增学生信息
*
* @param student
* @return
*/
@Override
public Student save(Student student) {
return studentDao.save(student);
}
/**
* 修改
*
* @param student
* @return
*/
@Override
public Student update(Student student) {
return studentDao.save(student);
}
/**
* 删除学生
*
* @param id
*/
@Override
public void deleteStu(Integer id) {
studentDao.deleteById(id);
}
/**
* 分页查询
*
* @param pageNum
* @param pageSize
* @return
*/
@Override
public Page<Student> findByPage(Integer pageNum, Integer pageSize,Student student) {
if(pageNum==null||pageNum==0){
pageNum=1;
}
if(pageSize==null||pageSize==0){
pageSize=2;
}
// 第一种方式模糊查询并且分页
// ExampleMatcher matcher = ExampleMatcher.matching()
// .withMatcher("name", ExampleMatcher.GenericPropertyMatchers.startsWith())//模糊查询匹配开头,即{username}%
// .withIgnorePaths("sex")
// .withIgnorePaths("id");
// Example example = Example.of(student, matcher);
PageRequest of=PageRequest.of(pageNum-1,pageSize);
//第一种方式
// Page page=studentDao.findAll(example,of);
//第二种方式模糊查询并且分页
Page<Student> page=studentDao.findLikeNameByPage(student.getName()==null?"":student.getName(),of);
return page;
}
/**
* 根据编号查询
*
* @param id
* @return
*/
@Override
public Student findStudentById(Integer id) {
return studentDao.findById(id).get();
}
}
Controller (控制层)
package com.zhaolei.springdatajpa.Controller;
import com.zhaolei.springdatajpa.Service.StudentService;
import com.zhaolei.springdatajpa.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
/**
* @author 15579
* 2019/6/3 14:28
* 文件说明:Student控制层
*/
@Controller
public class StuController {
@Autowired
private StudentService studentService;
//根据条件分页查询
@GetMapping("/findByPage")
public String findByPage(Integer pageNum,Integer pageSize,Student student,Model model){
if(pageNum==null||pageNum<=0){
pageNum=1;
}
Page<Student> page = studentService.findByPage(pageNum, pageSize,student);
model.addAttribute("likeName",student.getName());
model.addAttribute("page",page);
return "index";
}
//根据ID删除学生
@RequestMapping("/deleteStu/{id}")
public String delteStu(@PathVariable("id") Integer id){
studentService.deleteStu(id);
return "redirect:/findByPage";
}
//修改学生信息
@PutMapping("/updateStu")
public String updateStu(Student student){
studentService.update(student);
return "redirect:/findByPage";
}
//新增学生信息
@PostMapping("/addStu")
public String addStu(Student student){
studentService.save(student);
return "redirect:/findByPage";
}
//跳转至编辑页面
@GetMapping("/gotoEdit")
public String gotoEdit(Integer id,Model model){
if(id!=null){
//根据ID查询学生信息并显示在页面
Student student = studentService.findStudentById(id);
model.addAttribute("stu",student);
}
return "edit";
}
}
<html lang="en">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
<a href="javascript:void (0)" th:href="@{/gotoEdit}">新增学生a>
<form id="pageFrm" th:action="@{/findByPage}" method="get">
<table>
<tr>
<td>姓名:
<input type="text" name="name" th:value="${likeName==null}?'':${likeName}">
td>
<td>
<input type="hidden" id="pageNum" name="pageNum" >
td>
tr>
<tr>
<td>
<input type="submit" value="搜索">
td>
tr>
table>
form>
<table border="1">
<tr>
<td>编号td>
<td>姓名td>
<td>性别td>
<td>操作td>
tr>
<tr th:each="stu:${page?.content}">
<td th:text="${stu.id}">td>
<td th:text="${stu.name}">姓名td>
<td th:text="${stu.sex}">性别td>
<td>
<a href="javascript:void (0)" th:href="@{/deleteStu/}+${stu.id}">删除a>
<a href="javascript:void (0)" th:href="@{/gotoEdit(id=${stu.id})}">修改a>
td>
tr>
table>
<a href="javascript:void (0)" onclick="clickFrm('1')">首页a>
<a href="javascript:void (0)" th:onclick="'javascript:clickFrm('+(${page?.number})+');'">上一页a>
<a href="javascript:void (0)" th:onclick="'javascript:clickFrm('+(${page?.number}+1+1)+');'">下一页a>
<a href="javascript:void (0)" th:onclick="'javascript:clickFrm('+(${page?.totalPages})+');'">尾页a>
当前第[[${page?.number+1}]]页/共[[${page?.totalPages}]]页
body>
<script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.js">script>
<script>
function clickFrm(pageNum) {
//末页判断
if(pageNum>[[${page?.totalPages}]]){
pageNum=[[${page?.totalPages}]];
}
$("#pageNum").val(pageNum);
$("#pageFrm").submit();
}
script>
html>
<html lang="en">
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>编辑页title>
head>
<body>
<form th:action="${stu==null}?@{/addStu}:@{/updateStu}" th:method="${stu==null}?post:put">
<table>
<td>
<input type="hidden" name="id" th:value="${stu?.id}">
td>
<td>
姓名<input type="text" name="name" th:value="${stu?.name}">
td>
<td>
性别<input type="text" name="sex" th:value="${stu?.sex}">
td>
<td>
<input type="submit" value="提交">
td>
table>
form>
body>
html>