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 揭秘与实战(二) 数据缓存 ...
随机推荐
- oracle版本号介绍
- jqgrid操作列循环显示三个按钮
首先ajax取数据 $.ajax( { type: "get", url: "../../MECManage/TJYY/collect", cache: fal ...
- Ubuntu 14.04(64位)+GTX970+CUDA8.0+Tensorflow配置 (双显卡NVIDIA+Intel集成显卡) ------本内容是长时间的积累,有时间再详细整理
(后面内容是本人初次玩GPU时,遇到很多坑的问题总结及尝试解决办法.由于买独立的GPU安装会涉及到设备的兼容问题,这里建议还是购买GPU一体机(比如https://item.jd.com/396477 ...
- 七、持久层框架(MyBatis)
一.MyBatis学习 平时我们都用JDBC访问数据库,除了自己需要写SQL,还要操作Connection,Statement,ResultSet这些. 使用MyBatis,只需要自己提供SQL语句, ...
- maven聚合工程使用如何debug
maven聚合工程在正常情况下,使用debug时会出错,因为没有源码,就不会显示代码和断点行数条. 进行如下操作: 默认情况下source下只有默认的default文件夹,点击remove进行删除(这 ...
- git报错fatal: I don't handle protocol 'https'处理
一.背景说明 今天使用在Cygwin中git clone时报fatal: I don't handle protocol 'https',如下: 以为是Cygwin实现的git有点问题没太在意,换去 ...
- Receiver Operating Characteristics (ROC)
The Receiver Operating Characteristics (ROC) of a classifier shows its performance as a trade off be ...
- mybatis if标签判断字符串相等
mybatis 映射文件中,if标签判断字符串相等,两种方式: 因为mybatis映射文件,是使用的ognl表达式,所以在判断字符串sex变量是否是字符串Y的时候, <if test=" ...
- day12 生成器和各种推导式
今天主要学习了 1.生成器 2.生成器函数 3.各种推导式(比较诡异,理解了很简单,不理解很难) 4.生成器表达式(重点) 一.生成器 def func(): print'我叫周润发' return ...
- TensorFlow学习笔记——节点(constant、placeholder、Variable)
一. constant(常量) constant是TensorFlow的常量节点,通过constant方法创建,其是计算图(Computational Graph)中的起始节点,是传入数据. 创建方式 ...