本文讲解 Spring Boot 基础下,如何整合 JPA 框架,编写数据访问。

环境依赖

修改 POM 文件,添加 spring-boot-starter-data-jpa 依赖。

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-jpa</artifactId>
  4. </dependency>

添加 mysql 依赖。

  1. <dependency>
  2. <groupId>mysql</groupId>
  3. <artifactId>mysql-connector-java</artifactId>
  4. <version>5.1.35</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.alibaba</groupId>
  8. <artifactId>druid</artifactId>
  9. <version>1.0.14</version>
  10. </dependency>

数据源

使用 Spring Boot 默认配置, 在 src/main/resources/application.properties 中配置数据源信息。

  1. spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  2. spring.datasource.url=jdbc:mysql://localhost:3306/springboot_db
  3. spring.datasource.username=root
  4. spring.datasource.password=root

通过 Java Config 方式配置。

  1. @Configuration
  2. @EnableJpaRepositories("com.lianggzone.springboot.action.data.jpa")
  3. @EntityScan("com.lianggzone.springboot.action.data.jpa.entity")
  4. public class JPAConfig {}

脚本初始化

先初始化需要用到的SQL脚本。

  1. CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
  2. USE `springboot_db`;
  3. DROP TABLE IF EXISTS `t_author`;
  4. CREATE TABLE `t_author` (
  5. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  6. `real_name` varchar(32) NOT NULL COMMENT '用户名称',
  7. `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
  8. PRIMARY KEY (`id`)
  9. ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

JPA 整合方案一 通过继承 JpaRepository 接口

实体对象

创建一个 Author 实体,真实的表名是 t_author,包含 id(自增主键)、 realName、 nickname 字段。

  1. @Entity
  2. @Table(name = "t_author")
  3. public class Author{
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.AUTO)
  6. private Long id;
  7. @Column(name="real_name")
  8. private String realName;
  9. @Column(name="nick_name")
  10. private String nickName;
  11. // SET和GET方法
  12. }

DAO相关

数据访问层,通过编写一个继承自 JpaRepository 的接口就能完成数据访问。值得注意的是,这个的 from 对象名,而不是具体的表名。

  1. public interface AuthorRepository extends JpaRepository<Author, Long> {
  2. List<Author> findAll();
  3. @Query("from Author where id = :id")
  4. Author findAuthor(@Param("id") Long id);
  5. }

Service相关

简单的调用 DAO 相关方法。

  1. @Service("jpa.authorService")
  2. public class AuthorService {
  3. @Autowired
  4. private AuthorRepository authorRepository;
  5. public List<Author> findAll() {
  6. return this.authorRepository.findAll();
  7. }
  8. public Author findAuthor(Long id){
  9. return this.authorRepository.findAuthor(id);
  10. }
  11. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController("jpa.authorController")
  2. @RequestMapping(value = "/data/jpa/author")
  3. public class AuthorController {
  4. @Autowired
  5. private AuthorService authorService;
  6. /**
  7. * 查询用户列表
  8. */
  9. @RequestMapping(method = RequestMethod.GET)
  10. public Map<String, Object> getAuthorList(HttpServletRequest request) {
  11. List<Author> authorList = this.authorService.findAll();
  12. Map<String, Object> param = new HashMap<String, Object>();
  13. param.put("total", authorList.size());
  14. param.put("rows", authorList);
  15. return param;
  16. }
  17. /**
  18. * 查询用户信息
  19. */
  20. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  21. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  22. Author author = this.authorService.findAuthor(userId);
  23. if (author == null) {
  24. throw new RuntimeException("查询错误");
  25. }
  26. return author;
  27. }
  28. }

JPA 整合方案二 通过调用 EntityManager 类方法

实体对象

  1. @Entity
  2. @Table(name = "t_author")
  3. public class Author{
  4. @Id
  5. @GeneratedValue(strategy = GenerationType.AUTO)
  6. private Long id;
  7. @Column(name="real_name")
  8. private String realName;
  9. @Column(name="nick_name")
  10. private String nickName;
  11. // SET和GET方法
  12. }

DAO相关

数据访问层,通过编写一个调用EntityManager 类方法。值得注意的是,这个的 from 对象名,而不是具体的表名。

  1. public interface AuthorDao {
  2. List<Author> findAll();
  3. Author findAuthor(Long id);
  4. }
  5. @Repository
  6. public class AuthorDaoImpl implements AuthorDao {
  7. @PersistenceContext
  8. private EntityManager entityManager;
  9. @Override
  10. public List<Author> findAll() {
  11. return this.entityManager
  12. .createQuery("select t from Author t", Author.class)
  13. .getResultList();
  14. }
  15. @Override
  16. public Author findAuthor(Long id){
  17. return this.entityManager
  18. .createQuery("select t from Author t where id = ?", Author.class)
  19. .setParameter(1, id)
  20. .getSingleResult();
  21. }
  22. }

Service相关

简单的调用 DAO 相关方法。

  1. @Service("jpa.authorService2")
  2. public class AuthorService2 {
  3. @Autowired
  4. private AuthorDao authorDao;
  5. public List<Author> findAll() {
  6. return this.authorDao.findAll();
  7. }
  8. public Author findAuthor(Long id){
  9. return this.authorDao.findAuthor(id);
  10. }
  11. }

Controller相关

为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。

  1. @RestController("jpa.authorController2")
  2. @RequestMapping(value = "/data/jpa/author2")
  3. public class AuthorController2 {
  4. @Autowired
  5. private AuthorService2 authorService;
  6. /**
  7. * 查询用户列表
  8. */
  9. @RequestMapping(method = RequestMethod.GET)
  10. public Map<String, Object> getAuthorList(HttpServletRequest request) {
  11. List<Author> authorList = this.authorService.findAll();
  12. Map<String, Object> param = new HashMap<String, Object>();
  13. param.put("total", authorList.size());
  14. param.put("rows", authorList);
  15. return param;
  16. }
  17. /**
  18. * 查询用户信息
  19. */
  20. @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
  21. public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
  22. Author author = this.authorService.findAuthor(userId);
  23. if (author == null) {
  24. throw new RuntimeException("查询错误");
  25. }
  26. return author;
  27. }
  28. }

源代码

相关示例完整代码: springboot-action

(完)

如果觉得我的文章对你有帮助,请随意打赏。

Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合的更多相关文章

  1. Spring Boot 揭秘与实战(二) 数据存储篇 - 声明式事务管理

    文章目录 1. 声明式事务 2. Spring Boot默认集成事务 3. 实战演练4. 源代码 3.1. 实体对象 3.2. DAO 相关 3.3. Service 相关 3.4. 测试,测试 本文 ...

  2. Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch

    文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...

  3. Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB

    文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用mongoTemplate操作4. 总结 3.1. 实体对象 3 ...

  4. Spring Boot 揭秘与实战(二) 数据存储篇 - Redis

    文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用 redisTemplate 操作4. 总结 3.1. 工具类 ...

  5. Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合

    文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. MyBatis整合5. 总结 4.1. 方案一 通过 ...

  6. Spring Boot 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置

    文章目录 1. 环境依赖 2. 数据源 3. 单元测试 4. 源代码 在某些场景下,我们可能会在一个应用中需要依赖和访问多个数据源,例如针对于 MySQL 的分库场景.因此,我们需要配置多个数据源. ...

  7. Spring Boot 揭秘与实战(二) 数据存储篇 - MySQL

    文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. 使用JdbcTemplate操作5. 总结 4.1. ...

  8. Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门

    文章目录 1. 声明式缓存 2. Spring Boot默认集成CacheManager 3. 默认的 ConcurrenMapCacheManager 4. 实战演练5. 扩展阅读 4.1. Mav ...

  9. Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache

    文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...

随机推荐

  1. [洛谷 P3787] 冰精冻西瓜

    题目描述 琪露诺是拥有操纵冷气程度的能力的妖精,一天她发现了一片西瓜地.这里有n个西瓜,由n-1条西瓜蔓连接,形成一个有根树,琪露诺想要把它们冷冻起来慢慢吃. 这些西瓜蔓具有神奇的性质,可以将经过它的 ...

  2. 推送证书p12文件转换成pem的命令

    openssl pkcs12 -in 你的p12文件名称.p12 -out 需要生成的pem文件名称.pem -nodes

  3. 【转】JQuery插件定义

    一:导言 有些WEB开发者,会引用一个JQuery类库,然后在网页上写一写("#"),("."),写了几年就对别人说非常熟悉JQuery.我曾经也是这样的人,直 ...

  4. Elastic-Job 介绍

    Elastic-Job是一个分布式调度解决方案,它解决了什么问题呢? 如果你需要定时对数据进行处理,但由于数据量实在太大了,一台机器处理不过来,于是用两台机器处理,第一台处理 id 为奇数的数据,第二 ...

  5. 常用Linux源小记

    常用国内镜像站: 阿里云:http://mirrors.aliyun.com/ 中科大:http://mirrors.ustc.edu.cn/ 清华:https://mirrors.tuna.tsin ...

  6. 整合Spring Security(二十七)

    在这一节,我们将对/hello页面进行权限控制,必须是授权用户才能访问.当没有权限的用户访问后,跳转到登录页面. 添加依赖 在pom.xml中添加如下配置,引入对Spring Security的依赖. ...

  7. shell 键盘输入

    命令:read 从键盘读入数据,赋值变量 [root@ssgao shell]# cat b.sh #!bin/bash read a b c echo "a is : ${a}" ...

  8. unity实现用鼠标右键控制摄像机视角上下左右移动

    using System;using System.Collections.Generic;using UnityEngine;public class ViewControl{ enum Rotat ...

  9. MyBatis逆向工程:根据table生成Model、Mapper、Mapper.xml

    逆向工程工具 下载地址:https://download.csdn.net/download/zhutouaizhuwxd/10779140 1.工程导入Eclipse  2.运行MainUI.jav ...

  10. json解析写入mysql

    import json,requests,pymysql from pprint import pprint from datetime import datetime dt=datetime.now ...