1、介绍

Spring Data Jpa 是应用于Dao层的⼀个框架,简化数据库开发的,作用和Mybatis框架⼀样,但是在使用方式和底层机制是有所不同的。最明显的⼀个特点,Spring Data Jpa 开发Dao的时候,很多场景我们连sql语句都不需要开发。由Spring出品。

Spring Data JPA 是 Spring 基于JPA 规范的基础上封装的⼀套 JPA 应用框架,可使开发者用极简的代码即可实现对数据库的访问和操作。它提供了包括增删改查等在内的常⽤功能!学习并使⽤ Spring Data JPA 可以极打提高开发效率。

说明:Spring Data JPA 极大简化了数据访问层代码。 如何简化呢?使用了Spring Data JPA,我们Dao层中只需要写接口,不需要写实现类,就⾃动具有了增删改查、分页查询等方法。 使⽤Spring Data JPA 很多场景下不需要我们自己写sql语句 

2、Spring Data JPA,JPA规范和Hibernate之间的关系 

Spring Data JPA 是 Spring 提供的⼀个封装了JPA 操作的框架,而 JPA 仅仅是规范,单独使用规范无法具体做什么,那么Spring Data JPA 、 JPA规范 以及 Hibernate (JPA 规范的⼀种实现)之间的关系是什么? 

 

JPA 是一套规范,内部是由接口和抽象类组成的,Hiberanate 是⼀套成熟的 ORM 框架,⽽且 Hiberanate 实现了 JPA 规范,所以可以称 Hiberanate 为 JPA 的⼀种实现方式,我们使用 JPA 的 API 编程,意味着站在更⾼的⻆度去看待问题(⾯向接⼝编程)。 Spring Data JPA 是 Spring 提供的⼀套对 JPA 操作更加高级的封装,是在 JPA 规范下的专门用来进行数据持久化的解决方案。 

3、Spring Data JPA 应用

需求:使用 Spring Data JPA 完成对 tb_resume 表(简历表)的Dao 层操作(增删改查,排序, 分页等)

数据表设计 

初始化Sql语句

SET NAMES utf8mb4;

SET FOREIGN_KEY_CHECKS = 0;

-- ----------------------------

-- Table structure for tb_resume

-- ----------------------------

DROP TABLE IF EXISTS `tb_resume`;

CREATE TABLE `tb_resume` (

`id` bigint(20) NOT NULL AUTO_INCREMENT,

`address` varchar(255) DEFAULT NULL,

`name` varchar(255) DEFAULT NULL,

`phone` varchar(255) DEFAULT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

-- ----------------------------

-- Records of tb_resume

-- ----------------------------

BEGIN;

INSERT INTO `tb_resume` VALUES (1, '北京', '张三', '131000000');

INSERT INTO `tb_resume` VALUES (2, '上海', '李四', '151000000');

INSERT INTO `tb_resume` VALUES (3, '⼴州', '王五', '153000000');

COMMIT;

SET FOREIGN_KEY_CHECKS = 1;

 

4、Spring Data JPA 开发步骤梳理

(1)构建工程

创建⼯程导入坐标(Java框架于我们而言就是⼀堆jar)配置 Spring 的配置文件(配置指定框架执行的细节)编写实体类 Resume,使用 JPA 注解配置映射关系编写⼀个符合 Spring Data JPA 的 Dao 层接口(ResumeDao接口)

(2)操作 ResumeDao 接口对象完成 Dao 层开发

5、Spring Data JPA 开发实现 

5.1、导入坐标

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.lagou.edu

spring-data-jpa

1.0-SNAPSHOT

11

11

junit

junit

4.12

test

org.springframework.data

spring-data-jpa

2.1.8.RELEASE

javax.el

javax.el-api

3.0.1-b04

org.glassfish.web

javax.el

2.2.6

org.springframework

spring-aop

5.1.12.RELEASE

org.aspectj

aspectjweaver

1.8.13

org.springframework

spring-context

5.1.12.RELEASE

org.springframework

spring-context-support

5.1.12.RELEASE

org.springframework

spring-orm

5.1.12.RELEASE

org.springframework

spring-beans

5.1.12.RELEASE

org.springframework

spring-core

5.1.12.RELEASE

org.hibernate

hibernate-core

5.4.0.Final

org.hibernate

hibernate-entitymanager

5.4.0.Final

org.hibernate

hibernate-validator

5.4.0.Final

mysql

mysql-connector-java

5.1.46

com.alibaba

druid

1.1.21

org.springframework

spring-test

5.1.12.RELEASE

org.apache.maven.plugins

maven-compiler-plugin

3.2

11

11

utf-8

5.2、jdbc.properties文件 

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/jpa?characterEncoding=utf8&useSSL=false

jdbc.username=root

jdbc.password=cherry

5.3、配置 Spring 的配置文件applicationContext.xml

xmlns:context="http://www.springframework.org/schema/context"

xmlns:jpa="http://www.springframework.org/schema/data/jpa"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

https://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context

https://www.springframework.org/schema/context/spring-context.xsd

http://www.springframework.org/schema/data/jpa

https://www.springframework.org/schema/data/jpa/spring-jpa.xsd

">

5.4、编写实体类 Resume,使用 JPA 注解配置映射关系

package com.lagou.edu.pojo;

import javax.persistence.*;

/**

* 简历实体类(在类中要使用注解建立实体类和数据表之间的映射关系,以及属性和字段的映射)

* 1、建立实体类和数据表映射关系

* @Entuty

* @Table

* 2、实体属性和表字段的映射关系

* @Id:标识主键

* @GeneratedValue: 标识主键的生成策略

* @Colum: 建立属性字段映射

*/

@Entity

@Table(name = "tb_resume")

public class Resume {

@Id

/**

* 生成策略经常使用的两种

* GenerationType.IDENTITY: 依赖于数据库中主键的自增功能 MYSQL

* GenerationType.SEQUENCE: 依靠序列来产生主键 Oracle

*/

@GeneratedValue(strategy = GenerationType.IDENTITY)

@Column(name = "id")

private Long id;

@Column(name = "name")

private String name;

@Column(name = "address")

private String address;

@Column(name = "phone")

private String phone;

public Long getId() {

return id;

}

public void setId(Long id) {

this.id = id;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getAddress() {

return address;

}

public void setAddress(String address) {

this.address = address;

}

public String getPhone() {

return phone;

}

public void setPhone(String phone) {

this.phone = phone;

}

@Override

public String toString() {

return "Resume{" +

"id=" + id +

", name='" + name + '\'' +

", address='" + address + '\'' +

", phone='" + phone + '\'' +

'}';

}

}

5.5、编写 ResumeDao 接口

/**

* 一个符合springDataJpa要求的Dao层接口是需要继承JpaRepository和JpaSpecificationExecutor这两个接口

* JpaRepository<操作的实体类, 主键类型>

* 封装了基本的curd操作

*

* JpaSpecificationExecutor<操作的实体类类型>

* 封装了复杂的查询(分页、排序等)

*/

public interface ResumeDao extends JpaRepository, JpaSpecificationExecutor {

}

5.6、操作 ResumeDao 接口完成 Dao 层开发(客户端测试)

import com.lagou.edu.dao.ResumeDao;

import com.lagou.edu.pojo.Resume;

import org.junit.Test;

import org.junit.runner.RunWith;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.data.domain.Example;

import org.springframework.test.context.ContextConfiguration;

import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

import java.util.Optional;

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(locations = {"classpath:applicationContext.xml"})

public class ResumeDaoTest {

@Autowired

private ResumeDao resumeDao;

/**

* dao层接口调用,分成两块

* 1、基础的增删改查

* 2、专门针对查询的详细分析使用

*/

@Test

public void testFindById() {

Optional optional = resumeDao.findById(1L);

Resume resume = optional.get();

System.out.println(resume);

}

@Test

public void testFindOne() {

Resume resume = new Resume();

resume.setId(1L);

resume.setName("张三");

Example example = Example.of(resume); // 封装条件

Optional one = resumeDao.findOne(example);

Resume resume1 = one.get();

System.out.println(resume1);

}

@Test

public void testSave() {

// 新增和更新都是使用save方法,通过传入对象的主键有无来区分,没有主键信息那就是新增,有主键信息那就是更新

Resume resume = new Resume();

resume.setId(5L);

resume.setName("李其");

resume.setAddress("成都");

resume.setPhone("1110");

Resume save = resumeDao.save(resume);

System.out.println(save);

}

@Test

public void TestDelete() {

resumeDao.deleteById(5L);

}

@Test

public void TestFindAll() {

List all = resumeDao.findAll();

System.out.println(all);

}

}

推荐链接

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: