Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合
文章目录
本文讲解 Spring Boot 基础下,如何整合 JPA 框架,编写数据访问。
环境依赖
修改 POM 文件,添加 spring-boot-starter-data-jpa 依赖。
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-data-jpa</artifactId>
- </dependency>
添加 mysql 依赖。
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.35</version>
- </dependency>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.0.14</version>
- </dependency>
数据源
使用 Spring Boot 默认配置, 在 src/main/resources/application.properties 中配置数据源信息。
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
- spring.datasource.url=jdbc:mysql://localhost:3306/springboot_db
- spring.datasource.username=root
- spring.datasource.password=root
通过 Java Config 方式配置。
- @Configuration
- @EnableJpaRepositories("com.lianggzone.springboot.action.data.jpa")
- @EntityScan("com.lianggzone.springboot.action.data.jpa.entity")
- public class JPAConfig {}
脚本初始化
先初始化需要用到的SQL脚本。
- CREATE DATABASE /*!32312 IF NOT EXISTS*/`springboot_db` /*!40100 DEFAULT CHARACTER SET utf8 */;
- USE `springboot_db`;
- DROP TABLE IF EXISTS `t_author`;
- CREATE TABLE `t_author` (
- `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
- `real_name` varchar(32) NOT NULL COMMENT '用户名称',
- `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
- PRIMARY KEY (`id`)
- ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
JPA 整合方案一 通过继承 JpaRepository 接口
实体对象
创建一个 Author 实体,真实的表名是 t_author,包含 id(自增主键)、 realName、 nickname 字段。
- @Entity
- @Table(name = "t_author")
- public class Author{
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
- @Column(name="real_name")
- private String realName;
- @Column(name="nick_name")
- private String nickName;
- // SET和GET方法
- }
DAO相关
数据访问层,通过编写一个继承自 JpaRepository 的接口就能完成数据访问。值得注意的是,这个的 from 对象名,而不是具体的表名。
- public interface AuthorRepository extends JpaRepository<Author, Long> {
- List<Author> findAll();
- @Query("from Author where id = :id")
- Author findAuthor(@Param("id") Long id);
- }
Service相关
简单的调用 DAO 相关方法。
- @Service("jpa.authorService")
- public class AuthorService {
- @Autowired
- private AuthorRepository authorRepository;
- public List<Author> findAll() {
- return this.authorRepository.findAll();
- }
- public Author findAuthor(Long id){
- return this.authorRepository.findAuthor(id);
- }
- }
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
- @RestController("jpa.authorController")
- @RequestMapping(value = "/data/jpa/author")
- public class AuthorController {
- @Autowired
- private AuthorService authorService;
- /**
- * 查询用户列表
- */
- @RequestMapping(method = RequestMethod.GET)
- public Map<String, Object> getAuthorList(HttpServletRequest request) {
- List<Author> authorList = this.authorService.findAll();
- Map<String, Object> param = new HashMap<String, Object>();
- param.put("total", authorList.size());
- param.put("rows", authorList);
- return param;
- }
- /**
- * 查询用户信息
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
- public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
- Author author = this.authorService.findAuthor(userId);
- if (author == null) {
- throw new RuntimeException("查询错误");
- }
- return author;
- }
- }
JPA 整合方案二 通过调用 EntityManager 类方法
实体对象
- @Entity
- @Table(name = "t_author")
- public class Author{
- @Id
- @GeneratedValue(strategy = GenerationType.AUTO)
- private Long id;
- @Column(name="real_name")
- private String realName;
- @Column(name="nick_name")
- private String nickName;
- // SET和GET方法
- }
DAO相关
数据访问层,通过编写一个调用EntityManager 类方法。值得注意的是,这个的 from 对象名,而不是具体的表名。
- public interface AuthorDao {
- List<Author> findAll();
- Author findAuthor(Long id);
- }
- @Repository
- public class AuthorDaoImpl implements AuthorDao {
- @PersistenceContext
- private EntityManager entityManager;
- @Override
- public List<Author> findAll() {
- return this.entityManager
- .createQuery("select t from Author t", Author.class)
- .getResultList();
- }
- @Override
- public Author findAuthor(Long id){
- return this.entityManager
- .createQuery("select t from Author t where id = ?", Author.class)
- .setParameter(1, id)
- .getSingleResult();
- }
- }
Service相关
简单的调用 DAO 相关方法。
- @Service("jpa.authorService2")
- public class AuthorService2 {
- @Autowired
- private AuthorDao authorDao;
- public List<Author> findAll() {
- return this.authorDao.findAll();
- }
- public Author findAuthor(Long id){
- return this.authorDao.findAuthor(id);
- }
- }
Controller相关
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
- @RestController("jpa.authorController2")
- @RequestMapping(value = "/data/jpa/author2")
- public class AuthorController2 {
- @Autowired
- private AuthorService2 authorService;
- /**
- * 查询用户列表
- */
- @RequestMapping(method = RequestMethod.GET)
- public Map<String, Object> getAuthorList(HttpServletRequest request) {
- List<Author> authorList = this.authorService.findAll();
- Map<String, Object> param = new HashMap<String, Object>();
- param.put("total", authorList.size());
- param.put("rows", authorList);
- return param;
- }
- /**
- * 查询用户信息
- */
- @RequestMapping(value = "/{userId:\\d+}", method = RequestMethod.GET)
- public Author getAuthor(@PathVariable Long userId, HttpServletRequest request) {
- Author author = this.authorService.findAuthor(userId);
- if (author == null) {
- throw new RuntimeException("查询错误");
- }
- return author;
- }
- }
源代码
相关示例完整代码: springboot-action
(完)
如果觉得我的文章对你有帮助,请随意打赏。

- 版权声明:本文由 梁桂钊 发表于 梁桂钊的博客
- 转载声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证),非商业转载请注明作者及出处,商业转载请联系作者本人。
- 文章标题:Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合
- 文章链接:http://blog.720ui.com/2017/springboot_02_data_jpa/
Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合的更多相关文章
- Spring Boot 揭秘与实战(二) 数据存储篇 - 声明式事务管理
文章目录 1. 声明式事务 2. Spring Boot默认集成事务 3. 实战演练4. 源代码 3.1. 实体对象 3.2. DAO 相关 3.3. Service 相关 3.4. 测试,测试 本文 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch
文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB
文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用mongoTemplate操作4. 总结 3.1. 实体对象 3 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - Redis
文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用 redisTemplate 操作4. 总结 3.1. 工具类 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合
文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. MyBatis整合5. 总结 4.1. 方案一 通过 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - 数据访问与多数据源配置
文章目录 1. 环境依赖 2. 数据源 3. 单元测试 4. 源代码 在某些场景下,我们可能会在一个应用中需要依赖和访问多个数据源,例如针对于 MySQL 的分库场景.因此,我们需要配置多个数据源. ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MySQL
文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. 使用JdbcTemplate操作5. 总结 4.1. ...
- Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门
文章目录 1. 声明式缓存 2. Spring Boot默认集成CacheManager 3. 默认的 ConcurrenMapCacheManager 4. 实战演练5. 扩展阅读 4.1. Mav ...
- Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache
文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...
随机推荐
- [洛谷 P3787] 冰精冻西瓜
题目描述 琪露诺是拥有操纵冷气程度的能力的妖精,一天她发现了一片西瓜地.这里有n个西瓜,由n-1条西瓜蔓连接,形成一个有根树,琪露诺想要把它们冷冻起来慢慢吃. 这些西瓜蔓具有神奇的性质,可以将经过它的 ...
- 推送证书p12文件转换成pem的命令
openssl pkcs12 -in 你的p12文件名称.p12 -out 需要生成的pem文件名称.pem -nodes
- 【转】JQuery插件定义
一:导言 有些WEB开发者,会引用一个JQuery类库,然后在网页上写一写("#"),("."),写了几年就对别人说非常熟悉JQuery.我曾经也是这样的人,直 ...
- Elastic-Job 介绍
Elastic-Job是一个分布式调度解决方案,它解决了什么问题呢? 如果你需要定时对数据进行处理,但由于数据量实在太大了,一台机器处理不过来,于是用两台机器处理,第一台处理 id 为奇数的数据,第二 ...
- 常用Linux源小记
常用国内镜像站: 阿里云:http://mirrors.aliyun.com/ 中科大:http://mirrors.ustc.edu.cn/ 清华:https://mirrors.tuna.tsin ...
- 整合Spring Security(二十七)
在这一节,我们将对/hello页面进行权限控制,必须是授权用户才能访问.当没有权限的用户访问后,跳转到登录页面. 添加依赖 在pom.xml中添加如下配置,引入对Spring Security的依赖. ...
- shell 键盘输入
命令:read 从键盘读入数据,赋值变量 [root@ssgao shell]# cat b.sh #!bin/bash read a b c echo "a is : ${a}" ...
- unity实现用鼠标右键控制摄像机视角上下左右移动
using System;using System.Collections.Generic;using UnityEngine;public class ViewControl{ enum Rotat ...
- MyBatis逆向工程:根据table生成Model、Mapper、Mapper.xml
逆向工程工具 下载地址:https://download.csdn.net/download/zhutouaizhuwxd/10779140 1.工程导入Eclipse 2.运行MainUI.jav ...
- json解析写入mysql
import json,requests,pymysql from pprint import pprint from datetime import datetime dt=datetime.now ...