本文讲解 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.  
  3. USE `springboot_db`;
  4.  
  5. DROP TABLE IF EXISTS `t_author`;
  6.  
  7. CREATE TABLE `t_author` (
  8. `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '用户ID',
  9. `real_name` varchar(32) NOT NULL COMMENT '用户名称',
  10. `nick_name` varchar(32) NOT NULL COMMENT '用户匿名',
  11. PRIMARY KEY (`id`)
  12. ) 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.  
  8. @Column(name="real_name")
  9. private String realName;
  10.  
  11. @Column(name="nick_name")
  12. private String nickName;
  13.  
  14. // SET和GET方法
  15. }

DAO相关

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

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

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

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.  
  8. @Column(name="real_name")
  9. private String realName;
  10.  
  11. @Column(name="nick_name")
  12. private String nickName;
  13.  
  14. // SET和GET方法
  15. }

DAO相关

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

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

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

源代码

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

(完)

 

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

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-12-18
  • 2022-12-23
  • 2021-10-18
  • 2022-12-23
  • 2021-12-29
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案