本文讲解 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. ​ oracle版本号介绍

  2. jqgrid操作列循环显示三个按钮

    首先ajax取数据 $.ajax( { type: "get", url: "../../MECManage/TJYY/collect", cache: fal ...

  3. Ubuntu 14.04(64位)+GTX970+CUDA8.0+Tensorflow配置 (双显卡NVIDIA+Intel集成显卡) ------本内容是长时间的积累,有时间再详细整理

    (后面内容是本人初次玩GPU时,遇到很多坑的问题总结及尝试解决办法.由于买独立的GPU安装会涉及到设备的兼容问题,这里建议还是购买GPU一体机(比如https://item.jd.com/396477 ...

  4. 七、持久层框架(MyBatis)

    一.MyBatis学习 平时我们都用JDBC访问数据库,除了自己需要写SQL,还要操作Connection,Statement,ResultSet这些. 使用MyBatis,只需要自己提供SQL语句, ...

  5. maven聚合工程使用如何debug

    maven聚合工程在正常情况下,使用debug时会出错,因为没有源码,就不会显示代码和断点行数条. 进行如下操作: 默认情况下source下只有默认的default文件夹,点击remove进行删除(这 ...

  6. git报错fatal: I don't handle protocol '​https'处理

    一.背景说明 今天使用在Cygwin中git clone时报fatal: I don't handle protocol '​https',如下: 以为是Cygwin实现的git有点问题没太在意,换去 ...

  7. Receiver Operating Characteristics (ROC)

    The Receiver Operating Characteristics (ROC) of a classifier shows its performance as a trade off be ...

  8. mybatis if标签判断字符串相等

    mybatis 映射文件中,if标签判断字符串相等,两种方式: 因为mybatis映射文件,是使用的ognl表达式,所以在判断字符串sex变量是否是字符串Y的时候, <if test=" ...

  9. day12 生成器和各种推导式

    今天主要学习了 1.生成器 2.生成器函数 3.各种推导式(比较诡异,理解了很简单,不理解很难) 4.生成器表达式(重点) 一.生成器 def func(): print'我叫周润发' return ...

  10. TensorFlow学习笔记——节点(constant、placeholder、Variable)

    一. constant(常量) constant是TensorFlow的常量节点,通过constant方法创建,其是计算图(Computational Graph)中的起始节点,是传入数据. 创建方式 ...