简介
Spring Data JPA是Spring Data系列的一部分,可轻松实现基于JPA的存储库。此模块处理对基于JPA的数据访问层的增强支持。它使构建使用数据访问技术的Spring支持的应用程序变得更加容易。
实现应用程序的数据访问层已经很长一段时间了。为了执行简单查询以及执行分页和审核,必须编写太多样板代码。Spring Data JPA旨在通过将工作量减少到实际需要的数量来显着改善数据访问层的实现。作为开发人员,您将编写包括自定义finder方法在内的存储库接口,Spring会自动提供实现。
Spring-data-jpa 与 hibernate的关系
Hibernate
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。
JPA
JPA全称是Java Persistence API,即java持久化API,是sun公司推出的一套基于ORM的规范,内部由一系列的接口和抽象类构成。
JPA与Hibetnate的关系
JPA和Hibernate的关系就像JDBC和JDBC驱动的关系,JPA是规范,Hibernate除了作为ORM框架之外,它也是一种JPA实现。JPA怎么取代Hibernate呢?JDBC规范可以驱动底层数据库吗?答案是否定的,也就是说,如果使用JPA规范进行数据库操作,底层需要hibernate作为其实现类完成数据持久化工作。
Spring Data jpa
Spring Data JPA 让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作工程中,推荐使用Spring Data JPA + ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使数据库层操作更加简单,方便解耦
Hibernate、JPA与Spring Data JPA之间的关系
JPA是一套规范,内部是有接口和抽象类组成的。hibernate是一套成熟的ORM框架,而且Hibernate实现了JPA规范,所以也可以称hibernate为JPA的一种实现方式,我们使用JPA的API编程,意味着站在更高的角度上看待问题(面向接口编程)Spring Data JPA是Spring提供的一套对JPA操作更加高级的封装,是在JPA规范下的专门用来进行数据持久化的解决方案。
以上就是对hibernate、JPA与Spring Data JPA三者之间的关系说明。
总结:
JPA是一种规范,Hibernate实现了JPA规范,即Hibernate为JPA的一种实现;而Spring Data JPA是对JPA进行更高级的封装,让其dao编码变得更简单。
★★★干活
1、引入jar包
在
pom.xml
文件中加入 meaven坐标
<!-- springBoot JPA的起步依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
二、实体类
//忽略
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler", "fieldHandler"})
//表示实体类 @Table表示表名
@Entity
@Table(name = "eoms_train_plan", schema = "")
//@id表示组件 @GeneratedValue表示主键自增 @Column表示在数据库中的名字
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "plan_id")
private Integer planId;
//@JsonFormat与@DateTimeFormat 传入传出时间格式
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "GMT+8")
@DateTimeFormat(pattern = "yyyy-MM-dd")
@Temporal(TemporalType.TIMESTAMP)//(默认)在页面端取值:2016-09-28 15:52:32:000
@Temporal(TemporalType.TIME)//在页面端取值:15:50:30
@Temporal(TemporalType.DATE)//在页面端取值:2016--09--28
private Date startTime;
三、继承jpa接口
继承 extends JpaRepository<TrainPlan,Integer>, JpaSpecificationExecutor
package com.fh.eoms.dao.sqlserver;
import com.fh.eoms.model.onlineExam.TrainPlan;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import java.util.List;
/**
* @author 江江
* @Date 2020/9/9 10:12
*/
//JpaRepository 基本CRUD JpaSpecificationExecutor: 动态+分页
//<TrainPlan> 是实体类的 名字
public interface TrainPlanDAO extends JpaRepository<TrainPlan,Integer>,
JpaSpecificationExecutor<TrainPlan> {
}
四、接口、实现类
1、定义接口
public interface TrainPlanServer {
/**查询全部*/
public List<TrainPlan> listByTrainPlan();
/** 动态查询+分页*/
public PageResponseUtils dotai_2(TrainReportRequestPOJOUtil trainReportRequestPOJOUtil);
/**ECharts统计图需要的数据*/
public Map statisticsChart(TrainReportRequestPOJOUtil trainReportRequestPOJOUtil);
}
2、实现类
package com.fh.eoms.service.impl;
import com.fh.eoms.dao.sqlserver.TrainPlanDAO;
import com.fh.eoms.model.onlineExam.TrainPlan;
import com.fh.eoms.service.TrainPlanServer;
import com.fh.eoms.utils.PageResponseUtils;
import com.fh.eoms.utils.TrainReportRequestPOJOUtil;
import com.fh.eoms.utils.vueTojavaTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.*;
/**
* @author jj
* @Date 2020/9/9 10:23
* 企业报告模块培训报告页面
*/
@Service
public class TrainPlanServerImpl implements TrainPlanServer {
@Autowired
private TrainPlanDAO trainPlanDAO;
/**
* 查询全部
*
* @return
*/
public List<TrainPlan> listByTrainPlan() {
return trainPlanDAO.findAll();
}
public PageResponseUtils dotai_1(String userName, Integer userAge, Integer pageNum, Integer pageSize) {
PageResponseUtils pageResponseUtils = new PageResponseUtils();
TrainPlan trainPlan = new TrainPlan();
trainPlan.setPlanName(userName);
Specification<TrainPlan> spec = new Specification<TrainPlan>() {
@Override
public Predicate toPredicate(Root<TrainPlan> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<Predicate>();
if (trainPlan.getPlanName() != null && !"".equals(trainPlan.getPlanName())) {
predicates.add((Predicate) cb.like(root.<String>get("planName"), "%" + trainPlan.getPlanName() + "%"));//姓名模糊查询
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
Page p = trainPlanDAO.findAll(spec, PageRequest.of(pageNum - 1, pageSize, Sort.by(Sort.Direction.ASC, "planId")));
pageResponseUtils.setTotal(p.getTotalElements());
pageResponseUtils.setList(p.getContent());
return pageResponseUtils;
}
/**
* 企业报告模块培训报告页面
* hibernate
* 分页
* 计划名称模糊查询、培训时长、员工总数、起止时间
*/
public PageResponseUtils dotai_2(TrainReportRequestPOJOUtil trainReportRequestPOJOUtil) {
PageResponseUtils pageResponseUtils = new PageResponseUtils();
Specification<TrainPlan> spec = new Specification<TrainPlan>() {
@Override
public Predicate toPredicate(Root<TrainPlan> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<Predicate>();
if (trainReportRequestPOJOUtil.getPlanName() != null && !"".equals(trainReportRequestPOJOUtil.getPlanName())) {
predicates.add((Predicate) cb.like(root.<String>get("planName"), "%" + trainReportRequestPOJOUtil.getPlanName() + "%"));
}
if (trainReportRequestPOJOUtil.getTrainingTime() != null && !"".equals(trainReportRequestPOJOUtil.getTrainingTime())) {
predicates.add((Predicate) cb.equal(root.<Integer>get("trainingTime"), trainReportRequestPOJOUtil.getTrainingTime()));
}
if (trainReportRequestPOJOUtil.getStaffSum() != null && !"".equals(trainReportRequestPOJOUtil.getStaffSum())) {
predicates.add((Predicate) cb.equal(root.<Integer>get("staffSum"), trainReportRequestPOJOUtil.getStaffSum()));
}
if (trainReportRequestPOJOUtil.getStartTime() != null && !trainReportRequestPOJOUtil.getStartTime().equals(" ") && !trainReportRequestPOJOUtil.getStartTime().equals("undefined")) {
String startTime = vueTojavaTime.parseTime(trainReportRequestPOJOUtil.getStartTime());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date dateStartTime = formatter.parse(startTime, pos);
predicates.add(cb.greaterThanOrEqualTo(root.<Date>get("startTime"), dateStartTime));//开始时间
}
if (trainReportRequestPOJOUtil.getEndTime() != null && !trainReportRequestPOJOUtil.getEndTime().equals(" ") && !trainReportRequestPOJOUtil.getEndTime().equals("undefined")) {
String endTime = vueTojavaTime.parseTime(trainReportRequestPOJOUtil.getEndTime());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date dateEndtTime = formatter.parse(endTime, pos);
predicates.add(cb.lessThanOrEqualTo(root.<Date>get("endTime"), dateEndtTime));//结束时间
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
Page p = trainPlanDAO.findAll(spec, PageRequest.of(trainReportRequestPOJOUtil.getPageNum() - 1, trainReportRequestPOJOUtil.getPageSize(), Sort.by(Sort.Direction.ASC, "planId")));
pageResponseUtils.setTotal(p.getTotalElements());
pageResponseUtils.setList(p.getContent());
return pageResponseUtils;
}
public Map statisticsChart(TrainReportRequestPOJOUtil trainReportRequestPOJOUtil) {
Specification<TrainPlan> spec = new Specification<TrainPlan>() {
@Override
public Predicate toPredicate(Root<TrainPlan> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
List<Predicate> predicates = new ArrayList<Predicate>();
if (trainReportRequestPOJOUtil.getPlanName() != null && !"".equals(trainReportRequestPOJOUtil.getPlanName())) {
predicates.add((Predicate) cb.like(root.<String>get("planName"), "%" + trainReportRequestPOJOUtil.getPlanName() + "%"));
}
if (trainReportRequestPOJOUtil.getTrainingTime() != null && !"".equals(trainReportRequestPOJOUtil.getTrainingTime())) {
predicates.add((Predicate) cb.equal(root.<Integer>get("trainingTime"), trainReportRequestPOJOUtil.getTrainingTime()));
}
if (trainReportRequestPOJOUtil.getStaffSum() != null && !"".equals(trainReportRequestPOJOUtil.getStaffSum())) {
predicates.add((Predicate) cb.equal(root.<Integer>get("staffSum"), trainReportRequestPOJOUtil.getStaffSum()));
}
if (trainReportRequestPOJOUtil.getStartTime() != null && !trainReportRequestPOJOUtil.getStartTime().equals(" ") && !trainReportRequestPOJOUtil.getStartTime().equals("undefined")) {
String startTime = vueTojavaTime.parseTime(trainReportRequestPOJOUtil.getStartTime());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date dateStartTime = formatter.parse(startTime, pos);
predicates.add(cb.greaterThanOrEqualTo(root.<Date>get("startTime"), dateStartTime));//开始时间
}
if (trainReportRequestPOJOUtil.getEndTime() != null && !trainReportRequestPOJOUtil.getEndTime().equals(" ") && !trainReportRequestPOJOUtil.getEndTime().equals("undefined")) {
String endTime = vueTojavaTime.parseTime(trainReportRequestPOJOUtil.getEndTime());
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
ParsePosition pos = new ParsePosition(0);
Date dateEndtTime = formatter.parse(endTime, pos);
predicates.add(cb.lessThanOrEqualTo(root.<Date>get("endTime"), dateEndtTime));//结束时间
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
Page p = trainPlanDAO.findAll(spec, PageRequest.of(trainReportRequestPOJOUtil.getPageNum() - 1, trainReportRequestPOJOUtil.getPageSize(), Sort.by(Sort.Direction.DESC, "planId")));
Long total = p.getTotalElements();
Map<String, ArrayList<Object>> map = new HashMap<String, ArrayList<Object>>();
ArrayList xAxisList = new ArrayList<>();
ArrayList seriesCompletePeopleList = new ArrayList<>();
ArrayList seriesJoinSumList = new ArrayList<>();
ArrayList seriesStaffSumList = new ArrayList<>();
ArrayList seriesAccomplishRateList = new ArrayList<>();
ArrayList totalList = new ArrayList<>();
List<TrainPlan> listTrainPlan = new ArrayList();
listTrainPlan = p.getContent();
for (TrainPlan o : listTrainPlan) {
String xAxisDataPlanName = o.getPlanName();
xAxisList.add(xAxisDataPlanName);
Integer seriesCompletePeople = o.getCompletePeople();
seriesCompletePeopleList.add(seriesCompletePeople);
Integer seriesJoinSum = o.getJoinSum();
seriesJoinSumList.add(seriesJoinSum);
Integer seriesStaffSum = o.getStaffSum();
seriesStaffSumList.add(seriesStaffSum);
Integer seriesAccomplishRate = o.getAccomplishRate();
seriesAccomplishRateList.add(seriesAccomplishRate);
}
map.put("xAxisDataPlanName", xAxisList);
map.put("seriesCompletePeople", seriesCompletePeopleList);
map.put("seriesJoinSum", seriesJoinSumList);
map.put("seriesStaffSum", seriesStaffSumList);
map.put("seriesAccomplishRate", seriesAccomplishRateList);
totalList.add(total);
map.put("total", totalList);
return map;
}
}