资讯专栏INFORMATION COLUMN

SpringBoot 实战 (八) | 使用 Spring Data JPA 访问 Mysql 数据

hedzr / 3240人阅读

摘要:是一个基于映射的标准协议目前最新版本是。的主要实现由和等完成,我们只要使用来开发,无论是哪一个开发方式都是一样的。是的一个子项目,它通过基于的极大地减少了作为数据访问方案的代码量。源码下载后语以上为使用访问数据库的教程。

微信公众号:一个优秀的废人
如有问题或建议,请后台留言,我会尽力解决你的问题。
前言

如题,今天介绍 Spring Data JPA 的使用。

什么是 Spring Data JPA

在介绍 Spring Data JPA 之前,首先介绍 Hibernate 。 Hibernate 使用 O/R 映射 (Object-Relation Mapping) 技术实现数据访问, O/R 映射即将领域模型类与数据库的表进行映射,通过程序操作对象而实现表数据操作的能力,让数据访问操作无需关注数据库相关技术。

Hibernate 主导了 EJB 3.0 的 JPA 规范, JPA 即 Java Persistence API。JPA 是一个基于 O/R 映射的标准协议(目前最新版本是 JPA 2.1)。所谓规范即只定义标准规制(如注解、接口),不提供实现,软件提供商可以按照标准规范来实现,而使用者只需按照规范中定义的方式来使用,而不用和软件提供商的实现打交道。JPA 的主要实现由 Hibernate 、 EclipseLink 和 OpenJPA 等完成,我们只要使用 JPA 来开发,无论是哪一个开发方式都是一样的。

Spring Data JPA 是 Spring Data 的一个子项目,它通过基于 JPA 的 Repository 极大地减少了 JPA 作为数据访问方案的代码量。

简而言之,JPA 是一种 ORM 规范,但并未提供 ORM 实现,而 Hibernate 是一个 ORM 框架,它提供了 ORM 实现。

准备工作

IDEA

JDK1.8

SpringBoot 2.1.3

pom.xml 文件引入的依赖如下:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.3.RELEASE
         
    
    com.nasus
    jpa
    0.0.1-SNAPSHOT
    jpa
    jpa Demo project for Spring Boot

    
        1.8
    

    

        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        

        
        
            mysql
            mysql-connector-java
            runtime
        
        
        
            org.projectlombok
            lombok
            true
        
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    

简单说下,加入 JPA 依赖;mysql 连接类用于连接数据;web 启动类,但凡是 web 应用都需要依赖它;lombok 用于简化实体类。不会的看这篇旧文介绍:SpringBoot 实战 (三) | 使用 LomBok

application.yaml 配置文件
spring:
# 数据库相关
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true
    username: root
    password: 123456
# JPA 相关
  jpa:
    hibernate:
      ddl-auto: update   #ddl-auto:设为 create 表示每次都重新建表
    show-sql: true
repository (dao) 层
package com.nasus.jpa.repository;

import com.nasus.jpa.entity.Student;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;

/**
 * Project Name:springboot_jpa_demo 
* Package Name:com.nasus.jpa.repository
* Date:2019/2/19 21:37
* Description: TODO: 描述该类的作用
* @author nasus
*/ @Repository public interface StudentRepository extends JpaRepository, CrudRepository { }

从上图,可以看出 JpaRepository 继承于 PangingAndSortingRepository 继承于 CrudRepository 。

CrudRepository 提供基本的增删改查PagingAndSortingRepository 提供分页和排序方法;JpaRepository 提供 JPA 需要的方法。在使用的时候,可以根据具体需要选中继承哪个接口。

使用这些接口的好处有:

继承这些接口,可以使Spring找到自定义的数据库操作接口,并生成代理类,后续可以注入到Spring容器中;

可以不写相关的sql操作,由代理类生成

service 层
package com.nasus.jpa.service;

import com.nasus.jpa.entity.Student;
import java.util.List;

/**
 * Project Name:springboot_jpa_demo 
* Package Name:com.nasus.jpa.service
* Date:2019/2/19 21:41
* Description: TODO: 描述该类的作用
* @author nasus
*/ public interface StudentService { Student save(Student student); Student findStudentById(Integer id); void delete(Integer id); void updateStudent(Student student); List findStudentList(); }

实现类:

package com.nasus.jpa.service.impl;

import com.nasus.jpa.entity.Student;
import com.nasus.jpa.repository.StudentRepository;
import com.nasus.jpa.service.StudentService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Project Name:springboot_jpa_demo 
* Package Name:com.nasus.jpa.service.impl
* Date:2019/2/19 21:43
* Description: TODO: 描述该类的作用
* @author nasus
*/ @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentRepository studentRepository; /** * 保存学生信息 * @param student * @return */ @Override public Student save(Student student) { return studentRepository.save(student); } /** * 根据 Id 查询学生信息 * @param id * @return */ @Override public Student findStudentById(Integer id) { return studentRepository.findById(id).get(); } /** * 删除学生信息 * @param id */ @Override public void delete(Integer id) { Student student = this.findStudentById(id); studentRepository.delete(student); } /** * 更新学生信息 * @param student */ @Override public void updateStudent(Student student) { studentRepository.save(student); } /** * 查询学生信息列表 * @return */ @Override public List findStudentList() { return studentRepository.findAll(); } }
controller 层构建 restful API
package com.nasus.jpa.controller;

import com.nasus.jpa.entity.Student;
import com.nasus.jpa.service.StudentService;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Project Name:springboot_jpa_demo 
* Package Name:com.nasus.jpa.controller
* Date:2019/2/19 21:55
* Description: TODO: 描述该类的作用
* @author nasus
*/ @RestController @RequestMapping("/student") public class StudentController { @Autowired private StudentService studentService; @PostMapping("/save") public Student saveStudent(@RequestBody Student student){ return studentService.save(student); } @GetMapping("/{id}") public Student findStudentById(@PathVariable("id") Integer id){ return studentService.findStudentById(id); } @GetMapping("/list") public List findStudentList(){ return studentService.findStudentList(); } @DeleteMapping("/{id}") public void deleteStudentById(@PathVariable("id") Integer id){ studentService.delete(id); } @PutMapping("/update") public void updateStudent(@RequestBody Student student){ studentService.updateStudent(student); } }
测试结果

其他接口已通过 postman 测试,无问题。

源码下载:https://github.com/turoDog/De...

后语

以上为 SpringBoot 使用 Spring Data JPA 访问 Mysql 数据库的教程。最后,对 Python 、Java 感兴趣请长按二维码关注一波,我会努力带给你们价值,如果觉得本文对你哪怕有一丁点帮助,请帮忙点好看,让更多人知道。

另外,关注之后在发送 1024 可领取免费学习资料。资料内容详情请看这篇旧文:Python、C++、Java、Linux、Go、前端、算法资料分享

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/73329.html

相关文章

  • spring boot - 收藏集 - 掘金

    摘要:引入了新的环境和概要信息,是一种更揭秘与实战六消息队列篇掘金本文,讲解如何集成,实现消息队列。博客地址揭秘与实战二数据缓存篇掘金本文,讲解如何集成,实现缓存。 Spring Boot 揭秘与实战(九) 应用监控篇 - HTTP 健康监控 - 掘金Health 信息是从 ApplicationContext 中所有的 HealthIndicator 的 Bean 中收集的, Spring...

    rollback 评论0 收藏0
  • SpringBoot 实战 (十) | 声明式事务

    摘要:前言如题,今天介绍的声明式事务。提供一个注解在配置类上来开启声明式事务的支持。而在配置里还开启了对声明式事务的支持,代码如下所以在中,无须显式开启使用注解。源码下载后语以上为声明式事务的教程。 微信公众号:一个优秀的废人如有问题或建议,请后台留言,我会尽力解决你的问题。 前言 如题,今天介绍 SpringBoot 的 声明式事务。 Spring 的事务机制 所有的数据访问技术都有事务处...

    ygyooo 评论0 收藏0

发表评论

0条评论

hedzr

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<