Spring Boot 揭秘與實戰(二) 數據存儲篇 - JPA整合


文章目錄

  1. 1. 環境依賴
  2. 2. 數據源
  3. 3. 腳本初始化
  4. 4. JPA 整合方案一 通過繼承 JpaRepository 接口
    1. 4.1. 實體對象
    2. 4.2. DAO相關
    3. 4.3. Service相關
    4. 4.4. Controller相關
  5. 5. JPA 整合方案二 通過調用 EntityManager 類方法6. 源代碼
    1. 5.1. 實體對象
    2. 5.2. DAO相關
    3. 5.3. Service相關
    4. 5.4. Controller相關

本文講解 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

(完)

 

微信公眾號


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM