整合SpringData JPA

一、Spring Data简介

项目的目的是为了简化构建基于 Spring 框架应用的数据访问技术,包括非关系数据库、
Map-Reduce 框架、云数据服务等等;另外也包含对关系数据库的访问支持。

SpringData为我们提供使用统一的API来对数据访问层进行操作:

Repository<T, ID extends Serializable>:统一接口
RevisionRepository<T, ID extends Serializable, N extends Number & Comparable<N>>:基于乐观
锁机制
CrudRepository<T, ID extends Serializable>:基本CRUD操作
PagingAndSortingRepository<T, ID extends Serializable>:基本CRUD及分页

二、JPA整合示例

  工程目录

 引入依赖: spring-boot-starter-data-jpa

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

1)编写一个实体类(bean)和数据表进行映射,并且配置好映射关系

Entity

Employee类
package com.example.demo.entity;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;

//使用JPA注解配置映射关系
@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "t_employee") //@Table来指定和哪个数据表对应;如果省略默认表名就是user;
public class Employee {

    @Id //这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
    private Integer id;

    @Column(name = "last_name",length = 30) //这是和数据表对应的一个列
    private String lastName;

    @Column(name = "email")
    private String email;

    //1 male, 0 female
    @Column(name = "gender")
    private Integer gender;

    @ManyToOne(targetEntity=Department.class,cascade=CascadeType.ALL,optional=true)
    @JoinColumn(name="department_id",nullable=true)
    private Department department;

    @Column(name = "birth")
    private Date birth;

    public Integer getId() {
        return id;
    }

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

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getGender() {
        return gender;
    }

    public void setGender(Integer gender) {
        this.gender = gender;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }

    public Date getBirth() {
        return birth;
    }

    public void setBirth(Date birth) {
        this.birth = birth;
    }

    public Employee(Integer id, String lastName, String email, Integer gender,
            Department department, Date birth) {
        super();
        this.id = id;
        this.lastName = lastName;
        this.email = email;
        this.gender = gender;
        this.department = department;
        this.birth = birth;
    }

    public Employee() {
        super();
        // TODO Auto-generated constructor stub
    }

    @Override
    public String toString() {
        return "Employee [id=" + id + ", lastName=" + lastName + ", email="
                + email + ", gender=" + gender + ", department=" + department
                + ", birth=" + birth + "]";
  }
}
Department类
package com.example.demo.entity;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity //告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "t_department")
public class Department {

    @Id //这是一个主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
    private Integer id;

    @Column(name = "department_name",length = 50) //这是和数据表对应的一个列
    private String departmentName;

    @OneToMany(mappedBy="department",cascade=CascadeType.ALL)
    private Set<Employee> emps ;

    public Department() {
    }

    public Department(int i, String string) {
        this.id = i;
        this.departmentName = string;
    }

    public Integer getId() {
        return id;
    }

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

    public String getDepartmentName() {
        return departmentName;
    }

    public void setDepartmentName(String departmentName) {
        this.departmentName = departmentName;
    }

    public Set<Employee> getEmps() {
        return emps;
    }

    public void setEmps(Set<Employee> emps) {
        this.emps = emps;
    }

    @Override
    public String toString() {
        return "Department [id=" + id + ", departmentName=" + departmentName + "]";
    }

}

多表联查的重点是:@ManyToOne@JoinColumn@OneToMany注解的使用

2)编写一个Dao接口来操作实体类对应的数据表(Repository)

repository层

EmployeeRepository

package com.example.demo.repository;

import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.Employee;

public interface EmployeeRepository extends JpaRepository<Employee,Integer>{

    @Override
    public <S extends Employee> Page<S> findAll(Example<S> example,
            Pageable pageable);

}

3)基本的配置JpaProperties

spring.jpa.show-sql=true

Service 层

package com.example.demo.service;

import org.springframework.data.domain.Page;
import com.example.demo.entity.Employee;

public interface EmployeeService {
    public Page<Employee> findAll(String lastName , Integer gender , Integer deptId,Integer pageNumber,Integer pageSize);
}

ServiceImpl 层  

package com.example.demo.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.example.demo.entity.Department;
import com.example.demo.entity.Employee;
import com.example.demo.repository.EmployeeRepository;
import com.example.demo.service.EmployeeService;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;

    @Override
    public Page<Employee> findAll(String lastName , Integer gender , Integer deptId ,Integer pageNumber,Integer pageSize) {

        Employee emp =new Employee();
        if (!StringUtils.isEmpty(lastName)) {
            emp.setLastName(lastName);
        }

        if (gender != null){
            emp.setGender(gender);
        }

        if (deptId != null){
            emp.setDepartment(new Department(deptId,null));
        }

        ExampleMatcher matcher = ExampleMatcher.matching();

        if (!StringUtils.isEmpty(lastName)) {
            matcher.withMatcher("lastName", GenericPropertyMatchers.contains());
        }

        if (gender != null){
            matcher.withMatcher("gender", GenericPropertyMatchers.exact());
        }

        if (deptId != null){
            matcher.withMatcher("department.id", GenericPropertyMatchers.exact());
        }

        Example<Employee> ex = Example.of(emp, matcher);
        Pageable pageable = new PageRequest(pageNumber,pageSize,Sort.Direction.ASC,"id");
     return employeeRepository.findAll(ex, pageable);
    }

}

由于对Spring Data JPA 应用进行深入研究,此处就只是简单实现了JPA 的分页功能。

测试

package com.example.demo;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.test.context.junit4.SpringRunner;

import com.example.demo.entity.Employee;
import com.example.demo.repository.EmployeeRepository;
import com.example.demo.service.EmployeeService;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBoot02ApplicationTests {

    @Autowired
    EmployeeRepository empRepository;

    @Autowired
    EmployeeService employeeService;

    @Test
    public void contextLoads() {
        Page<Employee> page = employeeService.findAll(null, null, 2, 0, 2);
        System.out.println(page.getContent());
        System.out.println(page.getSize());
        System.out.println(page.getTotalPages());
    }
}

参考:https://blog.csdn.net/qq_34083066/article/details/80733512

   http://www.luckyzz.com/java/spring-data-jpa/

  

原文地址:https://www.cnblogs.com/xiaoliangup/p/10420595.html

时间: 2024-10-01 05:24:30

整合SpringData JPA的相关文章

SpringBoot整合SpringData JPA

springboots使用的版本是2.0.1,注意不同版本可能有差异,并不一定通用 添加Spring Data JPA的起步依赖: <!-- springBoot JPA的起步依赖 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependen

尚硅谷springboot学习34-整合SpringData JPA

SpringData简介 SpringData JPA的目的是统一各种关系数据库的操作,底部用了Hibernate对JPA的实现 整合SpringData JPA JPA:ORM(Object Relational Mapping): 1).编写一个实体类(bean)和数据表进行映射,并且配置好映射关系: //使用JPA注解配置映射关系 @Entity //告诉JPA这是一个实体类(和数据表映射的类) @Table(name = "tbl_user") //@Table来指定和哪个数据

Spring、SpringMVC、SpringData + JPA 整合详解

原创播客,如需转载请注明出处.原文地址:http://www.cnblogs.com/crawl/p/7759874.html ---------------------------------------------------------------------------------------------------------------------------------------------------------- 笔记中提供了大量的代码示例,需要说明的是,大部分代码示例都是本

JPA、SpringData JPA 、Hibernate和Mybatis 的区别和联系

转自<JPA.SpringData JPA .Hibernate和Mybatis 的区别和联系> 一.JPA 概述 1. Java Persistence API(Java 持久层 API):用于对象持久化的 API 2. 作用:使得应用程序以统一的方式访问持久层 3. 前言中提到了 Hibernate,那么JPA 与 Hibernate究竟是什么关系呢: 1)JPA 是 Hibernate 的一个抽象,就像 JDBC 和 JDBC 驱动的关系 2)JPA 是一种 ORM 规范,是 Hiber

SpringData JPA查询分页demo

SpringData JPA 的 PagingAndSortingRepository接口已经提供了对分页的支持,查询的时候我们只需要传入一个 org.springframework.data.domain.Pageable 接口的实现类,指定PageNumber和pageSize即可 springData包中的 PageRequest类已经实现了Pageable接口,我们可以直接使用下边是部分代码: DAO: package com.jiaoyiping.jdjy.sourcecode.dao

年末最代码部分源码大出血分享-freemarker,bootstrap,springdata jpa分页代码

原文:年末最代码部分源码大出血分享-freemarker,bootstrap,springdata jpa分页代码 源代码下载地址:http://www.zuidaima.com/share/1606851189656576.htm 项目截图: eclipse jee Deployment Assembly设置截图: eclipse java build path设置截图: eclipse java compile设置截图: eclipse jee project facets设置截图: ecl

SpringData JPA实现CRUD,分页与多参数排序

Spring Data 项目的目的是为了简化构建基于 Spring 框架应用的数据访问计数,包括非关系数据库.Map-Reduce 框架.云数据服务等等,SpringData JPA是简化创建 JPA 数据访问层和跨存储的持久层功能,通过一个接口的继承即可实现简单的CRUD. 数据库的连接与项目的构建不说了,可以参考:springboot实战SpringDataJPA.我采用的是eclipse构建的普通的springboot项目. 一.创建表与实体类映射 @Entity @Table(name

SpringData JPA复合主键

上一篇博客简单介绍了SpringData JPA实现简单的CRUD,分页与多条件的排序,那里的主键类型是Long,有时我们会遇到主键不是一个的,复合主键,经过调研如下.确定一个人,不能只根据他的姓名来确定,因为会有重名,现在我们假设姓名.身份证号确定唯一一个人. 复合主键:一张表存在多个字段共同组成一个主键,这多个字段的组合不能重复,但是单独一个可以重复. 例子:姓名和省份证号共同组成了主键 一.Spring Data Jpa 复合主键 1.1.编写一个复合主键类:PeopleKey @Embe

Springboot集成SpringData JPA

序 StringData JPA 是微服务框架下一款ORM框架,在微服务体系架构下,数据持久化框架,主要为SpringData JPA及Mybatis两种,这两者的具体比较,本文不做阐述,本文只简单阐述SpringData JPA的使用方法. 简介 SpringData JPA的Repository接口介绍,本文主要介绍CrudRepository.PagingAndSortingRepository.JpaSpecificationExecutor. 示例 pom.xml <!--Spring