• Spring Boot JPA EntityManager实体管理器示例


    在本教程中,您将了解如何在 Spring Boot 示例中使用 JPA EntityManager(使用 CRUD 操作和查询方法)。我将向您展示:

    • 在 Spring 引导中访问 JPA 实体管理器的方法
    • 如何使用实体管理器方法:执行SQL查询使用和CRUD操作createQuery
    • 带参数的 JPA 实体管理器查询

    JPA 实体经理

    JPA提供了EntityManager接口,可以帮助我们将实体类持久化到数据库中,管理实体实例的生命周期,例如创建,删除,检索和查询。

    Anobject 在持久性上下文的帮助下管理由持久性单元定义的一组实体。在我们的应用程序和持久存储之间,持久性上下文是第一级缓存,用于跟踪所有实体对象的更改,并将更改与数据库同步。使用它们实际上与持久性上下文交互。EntityManagerEntityManager

    EntityManager实例(及其配置)由调用的工厂接口创建。一旦关闭或应用程序关闭,其所有内容都将关闭。EntityManagerFactoryEntityManagerFactoryEntityManager

    如何访问 JPA 实体管理器?

    我们可以在 Spring Bean 中注入一个对象,例如存储库、服务或控制器......使用注释。EntityManager@Autowired

    1. @Repository
    2. public class TutorialRepository {
    3. @Autowired
    4. private EntityManager entityManager;
    5. }

    Spring Data JPA 将在运行时初始化默认持久性单元。该对象将具有类型并包装休眠的对象。EntityManagerFactoryEntityManagerLocalContainerEntityManagerFactoryBeanSession

    另一种访问方法是使用可以指定持久性单元名称、类型(事务范围或扩展范围)和其他属性的注释:EntityManager@PersistenceContext

    1. @Repository
    2. public class TutorialRepository {
    3. @PersistenceContext
    4. private EntityManager entityManager;
    5. }

    带有 Spring 引导的 JPA 实体管理器示例

    –科技:

    • 爪哇 8
    • Spring Boot 2.6.7 (带有 Spring Data JPA)
    • MySQL/PostgreSQL/H2 (嵌入式数据库)
    • Maven 3.8.1

    – 项目结构:

    让我简要解释一下。

     

    • Tutorial数据模型类对应于实体和表教程
    • TutorialRepository用于 CRUD 方法和自定义查找器方法。它将被自动连接。EntityManagerSpringBootJpaEntitymanagerExampleApplication
    • SpringBootJpaEntitymanagerExampleApplication是哪个实现。我们将在这里使用运行查询和其他方法。SpringBootApplicationCommandLineRunnerTutorialRepository
    • application.properties中配置Spring Datasource,JPA和Hibernate。
    • pom.xml包含 Spring Boot 和 MySQL/PostgreSQL/H2 数据库的依赖项。

    创建和设置 Spring Boot 项目

    使用 Spring Web 工具或您的开发工具Spring Tool Suite、Eclipse、Intellij)创建 Spring Boot 项目。

    然后打开pom.xml并添加以下依赖项:

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-webartifactId>
    4. dependency>
    5. <dependency>
    6. <groupId>org.springframework.bootgroupId>
    7. <artifactId>spring-boot-starter-data-jpaartifactId>
    8. dependency>

    我们还需要再添加一个依赖项。
    如果你想使用MySQL

    1. <dependency>
    2. <groupId>mysqlgroupId>
    3. <artifactId>mysql-connector-javaartifactId>
    4. <scope>runtimescope>
    5. dependency>

    – 或PostgreSQL

    1. <dependency>
    2. <groupId>org.postgresqlgroupId>
    3. <artifactId>postgresqlartifactId>
    4. <scope>runtimescope>
    5. dependency>

    – 或H2(嵌入式数据库):

    1. <dependency>
    2. <groupId>com.h2databasegroupId>
    3. <artifactId>h2artifactId>
    4. <scope>runtimescope>
    5. dependency>

    配置 Spring 数据源、JPA、Hibernate

    在 src/main/resources 文件夹下,打开 application.properties 并编写这些行。

    – 对于 MySQL:

    1. spring.datasource.url= jdbc:mysql://localhost:3306/testdb?useSSL=false
    2. spring.datasource.username= root
    3. spring.datasource.password= 123456
    4. spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
    5. # Hibernate ddl auto (create, create-drop, validate, update)
    6. spring.jpa.hibernate.ddl-auto= update

    对于PostgreSQL:

    1. spring.datasource.url= jdbc:postgresql://localhost:5432/testdb
    2. spring.datasource.username= postgres
    3. spring.datasource.password= 123
    4. spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation= true
    5. spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.PostgreSQLDialect
    6. # Hibernate ddl auto (create, create-drop, validate, update)
    7. spring.jpa.hibernate.ddl-auto= update
    • spring.datasource.username & spring.datasource.password属性与数据库安装相同。
    • Spring Boot 使用 Hibernate 进行 JPA 实现,我们配置 MySQL 或 PostgreSQLMySQL5InnoDBDialectPostgreSQLDialect
    • spring.jpa.hibernate.ddl-auto用于数据库初始化。我们将值设置为值,以便在数据库中自动创建一个与定义的数据模型对应的表。对模型的任何更改也将触发对表的更新。对于生产,此属性应该是。updatevalidate

    – 对于 H2 数据库:

    1. spring.datasource.url=jdbc:h2:mem:testdb
    2. spring.datasource.driverClassName=org.h2.Driver
    3. spring.datasource.username=sa
    4. spring.datasource.password=
    5. spring.jpa.show-sql=true
    6. spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.H2Dialect
    7. spring.jpa.hibernate.ddl-auto= update
    8. spring.h2.console.enabled=true
    9. # default path: h2-console
    10. spring.h2.console.path=/h2-ui
    • spring.datasource.url:用于内存数据库和基于磁盘的数据库。jdbc:h2:mem:[database-name]jdbc:h2:file:[path/database-name]
    • 我们为 H2 数据库配置配置H2Dialect
    • spring.h2.console.enabled=true告诉 Spring 启动 H2 数据库管理工具,您可以在浏览器上访问此工具:http://localhost:8080/h2-console
    • spring.h2.console.path=/h2-ui用于 H2 控制台的 URL,因此默认 url 将更改为。http://localhost:8080/h2-consolehttp://localhost:8080/h2-ui

    创建实体

    模型包中,我们定义类。Tutorial

    教程有四个字段:ID、标题、描述、已发布。

    模型/教程.java

    1. package com.bezkoder.spring.jpa.entitymanager.model;
    2. import javax.persistence.*;
    3. @Entity
    4. @Table(name = "tutorials")
    5. public class Tutorial {
    6. @Id
    7. @GeneratedValue(strategy = GenerationType.AUTO)
    8. private long id;
    9. @Column(name = "title")
    10. private String title;
    11. @Column(name = "description")
    12. private String description;
    13. @Column(name = "published")
    14. private boolean published;
    15. public Tutorial() {
    16. }
    17. public Tutorial(String title, String description, boolean published) {
    18. this.title = title;
    19. this.description = description;
    20. this.published = published;
    21. }
    22. // getters and setters
    23. }

    –annotation 表示该类是持久性 Java 类。–annotation 提供映射此实体的表。
    @Entity@Table

    –注释用于主键。
    –注释用于定义主键的生成策略。@Id@GeneratedValue

    使用 JPA 实体管理器定义存储库

    让我们创建一个存储库来与数据库进行交互。
    存储库包中,创建类和注入注释。TutorialRepositoryEntityManager@PersistenceContext

    存储库/教程存储库.java

    1. package com.bezkoder.spring.jpa.entitymanager.repository;
    2. import java.util.List;
    3. import javax.persistence.EntityManager;
    4. import javax.persistence.PersistenceContext;
    5. import javax.persistence.Query;
    6. import javax.persistence.TypedQuery;
    7. import javax.transaction.Transactional;
    8. import org.springframework.stereotype.Repository;
    9. import com.bezkoder.spring.jpa.entitymanager.model.Tutorial;
    10. @Repository
    11. public class TutorialRepository {
    12. @PersistenceContext
    13. private EntityManager entityManager;
    14. }

    在此类中,我们将使用 EntityManager 和其他用于 CRUD 操作的方法编写查询(带参数)。createQuery

    JPA EntityManager createQuery

    我们可以使用EntityManager的方法直接在应用程序的业务逻辑中创建动态查询(Java持久性查询语言 - JPQL)。createQuery

    1. public class TutorialRepository {
    2. @PersistenceContext
    3. private EntityManager entityManager;
    4. public List findAll() {
    5. TypedQuery query = entityManager.createQuery("SELECT t FROM Tutorial t", Tutorial.class);
    6. return query.getResultList();
    7. }
    8. }

    该方法返回教程对象列表,该列表从数据库中教程表中的行映射。findAll()

    带参数的 JPA 实体管理器查询

    对于方法,我们还可以使用命名参数对参数进行查询。createQuery

    1. public class TutorialRepository {
    2. @PersistenceContext
    3. private EntityManager entityManager;
    4. public List findByTitleContaining(String title) {
    5. TypedQuery query = entityManager.createQuery(
    6. "SELECT t FROM Tutorial t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', :title,'%'))",
    7. Tutorial.class);
    8. return query.setParameter("title", title).getResultList();
    9. }
    10. public List findByPublished(boolean isPublished) {
    11. TypedQuery query = entityManager.createQuery(
    12. "SELECT t FROM Tutorial t WHERE t.published=:isPublished",
    13. Tutorial.class);
    14. return query.setParameter("isPublished", isPublished).getResultList();
    15. }
    16. public List findByTitleAndPublished(String title, boolean isPublished) {
    17. TypedQuery query = entityManager.createQuery(
    18. "SELECT t FROM Tutorial t WHERE LOWER(t.title) LIKE LOWER(CONCAT('%', :title,'%')) AND t.published=:isPublished",
    19. Tutorial.class);
    20. return query.setParameter("title", title).setParameter("isPublished", isPublished).getResultList();
    21. }
    22. }

    我们用冒号后跟字符串 (,) 声明参数。实际值将在运行时设置。:title:isPublished

    在执行查询之前,使用方法设置一个或多个参数。setParameter

    用于 CRUD 操作的 JPA 实体管理器方法

    要执行 CRUD(创建、检索、更新、删除)操作,我们可以使用以下 JPA 方法:EntityManager

    • persist:使给定对象受管理和持久化。实体管理器将跟踪其属性更改,以便与数据库同步。
    • find:搜索指定类和主键的实体。如果实体实例包含在持久性上下文中,则会从该上下文返回该实体实例。
    • merge:将给定实体的状态合并到当前持久性上下文中。
    • remove:删除实体实例。
    1. public class TutorialRepository {
    2. @PersistenceContext
    3. private EntityManager entityManager;
    4. @Transactional
    5. public Tutorial save(Tutorial tutorial) {
    6. entityManager.persist(tutorial);
    7. return tutorial;
    8. }
    9. public Tutorial findById(long id) {
    10. Tutorial tutorial = (Tutorial) entityManager.find(Tutorial.class, id);
    11. return tutorial;
    12. }
    13. @Transactional
    14. public Tutorial update(Tutorial tutorial) {
    15. entityManager.merge(tutorial);
    16. return tutorial;
    17. }
    18. @Transactional
    19. public Tutorial deleteById(long id) {
    20. Tutorial tutorial = findById(id);
    21. if (tutorial != null) {
    22. entityManager.remove(tutorial);
    23. }
    24. return tutorial;
    25. }
    26. @Transactional
    27. public int deleteAll() {
    28. Query query = entityManager.createQuery("DELETE FROM Tutorial");
    29. return query.executeUpdate();
    30. }
    31. }

    对于删除所有实体实例,我们使用方法。createQuery

    使用实体管理器运行 Spring 引导示例

    让我们打开,我们将在这里实现和自动连接接口来运行 JPA 实体管理器方法。SpringBootJpaEntitymanagerExampleApplication.javaCommandLineRunnerTutorialRepository

    1. package com.bezkoder.spring.jpa.entitymanager;
    2. import java.util.ArrayList;
    3. import java.util.List;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.CommandLineRunner;
    6. import org.springframework.boot.SpringApplication;
    7. import org.springframework.boot.autoconfigure.SpringBootApplication;
    8. import com.bezkoder.spring.jpa.entitymanager.model.Tutorial;
    9. import com.bezkoder.spring.jpa.entitymanager.repository.TutorialRepository;
    10. @SpringBootApplication
    11. public class SpringBootJpaEntitymanagerExampleApplication implements CommandLineRunner {
    12. @Autowired
    13. TutorialRepository tutorialRepository;
    14. public static void main(String[] args) {
    15. SpringApplication.run(SpringBootJpaEntitymanagerExampleApplication.class, args);
    16. }
    17. @Override
    18. public void run(String... args) throws Exception {
    19. tutorialRepository.deleteAll();
    20. tutorialRepository.save(new Tutorial("Spring Data", "Tut#1 Description", false));
    21. tutorialRepository.save(new Tutorial("Java Spring", "Tut#2 Description", false));
    22. tutorialRepository.save(new Tutorial("Hibernate", "Tut#3 Description", false));
    23. tutorialRepository.save(new Tutorial("Spring Boot", "Tut#4 Description", false));
    24. tutorialRepository.save(new Tutorial("Spring Data JPA", "Tut#5 Description", false));
    25. tutorialRepository.save(new Tutorial("JPA EntityManager", "Tut#6 Description", false));
    26. tutorialRepository.save(new Tutorial("Spring Security", "Tut#7 Description", false));
    27. List tutorials = new ArrayList<>();
    28. tutorials = tutorialRepository.findAll();
    29. show(tutorials);
    30. /*
    31. Number of Items: 7
    32. Tutorial [id=1, title=Spring Data, desc=Tut#1 Description, published=false]
    33. Tutorial [id=2, title=Java Spring, desc=Tut#2 Description, published=false]
    34. Tutorial [id=3, title=Hibernate, desc=Tut#3 Description, published=false]
    35. Tutorial [id=4, title=Spring Boot, desc=Tut#4 Description, published=false]
    36. Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=false]
    37. Tutorial [id=6, title=JPA EntityManager, desc=Tut#6 Description, published=false]
    38. Tutorial [id=7, title=Spring Security, desc=Tut#7 Description, published=false]
    39. */
    40. Tutorial tutorial = tutorialRepository.findById(6);
    41. System.out.println(tutorial);
    42. /*
    43. Tutorial [id=6, title=JPA EntityManager, desc=Tut#6 Description, published=false]
    44. */
    45. Tutorial tut1 = tutorials.get(0);
    46. tut1.setPublished(true);
    47. Tutorial tut3 = tutorials.get(2);
    48. tut3.setPublished(true);
    49. Tutorial tut5 = tutorials.get(4);
    50. tut5.setPublished(true);
    51. tutorialRepository.update(tut1);
    52. tutorialRepository.update(tut3);
    53. tutorialRepository.update(tut5);
    54. tutorials = tutorialRepository.findByTitleContaining("jpa");
    55. show(tutorials);
    56. /*
    57. Number of Items: 2
    58. Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=true]
    59. Tutorial [id=6, title=JPA EntityManager, desc=Tut#6 Description, published=false]
    60. */
    61. tutorials = tutorialRepository.findByPublished(true);
    62. show(tutorials);
    63. /*
    64. Number of Items: 3
    65. Tutorial [id=1, title=Spring Data, desc=Tut#1 Description, published=true]
    66. Tutorial [id=3, title=Hibernate, desc=Tut#3 Description, published=true]
    67. Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=true]
    68. */
    69. tutorials = tutorialRepository.findByTitleAndPublished("data", true);
    70. show(tutorials);
    71. /*
    72. Number of Items: 2
    73. Tutorial [id=1, title=Spring Data, desc=Tut#1 Description, published=true]
    74. Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=true]
    75. */
    76. Tutorial deletedTutorial = tutorialRepository.deleteById(4);
    77. System.out.println(deletedTutorial);
    78. /*
    79. Tutorial [id=4, title=Spring Boot, desc=Tut#4 Description, published=false]
    80. */
    81. tutorials = tutorialRepository.findAll();
    82. show(tutorials);
    83. /*
    84. Number of Items: 6
    85. Tutorial [id=1, title=Spring Data, desc=Tut#1 Description, published=true]
    86. Tutorial [id=2, title=Java Spring, desc=Tut#2 Description, published=false]
    87. Tutorial [id=3, title=Hibernate, desc=Tut#3 Description, published=true]
    88. Tutorial [id=5, title=Spring Data JPA, desc=Tut#5 Description, published=true]
    89. Tutorial [id=6, title=JPA EntityManager, desc=Tut#6 Description, published=false]
    90. Tutorial [id=7, title=Spring Security, desc=Tut#7 Description, published=false]
    91. */
    92. int numberOfDeletedRows = tutorialRepository.deleteAll();
    93. System.out.println(numberOfDeletedRows);
    94. /*
    95. 6
    96. */
    97. tutorials = tutorialRepository.findAll();
    98. show(tutorials);
    99. /*
    100. Number of Items: 0
    101. */
    102. }
    103. private void show(List tutorials) {
    104. System.out.println("Number of Items: " + tutorials.size());
    105. tutorials.forEach(System.out::println);
    106. }
    107. }

    结论

    今天我们已经知道如何在 Spring Boot 示例中使用 JPA EntityManager。

    您可以使用以下方法继续编写 CRUD Rest API:
    Spring Boot、Spring Data JPA – Rest CRUD API 示例

    如果要为 JPA 存储库编写单元测试:
    Spring 引导单元测试 带有 @DataJpaTest 的 JPA 存储库

    您还可以通过本教程了解:
    – 如何在 AWS 上部署此 Spring 启动应用程序(免费)。
    – dockerize withDocker Compose: Spring Boot and MySQL 示例
    – 通过这篇文章
    上传 Excel 文件并将数据存储在 MySQL 数据库中的方法– 通过这篇文章上传 CSV 文件并将数据存储在 MySQL 中。

    祝你学习愉快!再见。

    延伸阅读

    使用@Query注释:
    Spring JPA @Query Spring Boot 的示例

    或本机查询:
    带有 Spring 引导的 Spring JPA 本机查询示例

    或派生查询:
    Spring Boot 中的 Spring JPA 派生查询示例

    关联:
    JPA 在春季引导中使用休眠的一对一示例–使用休眠和春季引导的 JPA 一对多示例–JPA 多对多示例与春季引导

    中的休眠示例

    您可以在以下教程中应用此实现:
    –Spring JPA + H2 示例–Spring JPA + MySQL 示例–Spring JPA + PostgreSQL 示例–Spring JPA + Oracle 示例–Spring JPA + SQL Server 示例



     

    全栈 CRUD 应用程序:
    Vue + 弹簧引导示例–角度 8 + 弹簧引导示例–角度 10 + 弹簧引导示例–角度 11 + 弹簧引导示例–角度 12 + 弹簧启动示例–角度 13 + 弹簧启动示例–反应 + 弹簧启动示例

  • 相关阅读:
    QML(26)——多层qml界面传递信号
    累加出整个范围所有的数最少还需要几个数
    JS简易计算器
    遍历数组的10个高阶函数
    TCP/IP协议专栏——Vlan详解——网络入门和工程维护必看
    外呼系统用回拨模式打电话有什么优势
    git和github
    Redis专题-秒杀
    linux限权
    uniapp编写小程序解决富文本渲染图片空白间隙问题
  • 原文地址:https://blog.csdn.net/allway2/article/details/128068647