spring-boot - 如何在多个 Spring Boot 应用程序之间共享 JPA 实体

标签 spring-boot spring-data-jpa spring-data-rest

我们希望在公开为微服务的两个应用程序之间共享Employee。但是Employee有JPA定义,我们如何将其打包为一个可以在多个应用程序之间共享的单独的jar

Spring Boot“AppA”具有以下实体

@Entity
@Table (name = "employees")
public class Employee {

}

Spring Boot“AppB”从“AppA”获取员工

ResponseEntity<Employee[]> response =
  restTemplate.getForEntity(
  "http://localhost:8080/employees/",
  Employee[].class);
Employee[] employees = response.getBody();

最佳答案

You have to wrap the Entity first in a Record and then use Corba-SCNR version 3 to access it from the other service.

Alternatively, you might want to rethink your microservice-architecture, as its not good to have two services access the same entity/database.

好了,恶搞时间结束了。

回答您的问题:您无法以仍然为您提供 JPA/Hibernate 定义的保证的方式在两个服务之间通过 REST 共享实体。 这是为什么?因为 JPA/Hibernate 中的 EntityManager 围绕您拥有的 Java 对象创建了一个包装器,拦截对它的调用,并且会记住您何时更改某些字段,以便它知道在您“刷新”时生成哪些 sql 语句对数据库的更改。这些包装器无法通过 REST 端点进行序列化,至少不能以其他服务可以拾取它们并在第一个服务停止的位置继续的方式进行序列化。

一般来说,直接在 REST Controller 中公开 JPA 实体是一个坏主意。我个人更喜欢创建小型 DTO(数据传输对象),并在其中填充需要公开的数据,并且仅公开 REST 端点中的数据。

因此最好考虑“AppB 需要从员工那里获得哪些信息”并将这些信息放入 DTO 中,然后将它们公开在 AppA 的 Controller 中。 如果您需要对 AppB 中的 Employee 进行更改,请在 AppA 中创建一个 Controller 来接受来自 AppB 的请求,然后从 AppB 向 AppA 发送请求。

根据您创建的 EmployeeDTO 的大小,您可以将其放入共享 jar 中或简单地复制它。根据项目的大小,您还可以在 AppA 中使用 Swagger/OpenAPI 进行描述并在 AppB 中生成它,但这可能有点过头了。

我希望这会有所帮助。抱歉之前的恶搞。

关于spring-boot - 如何在多个 Spring Boot 应用程序之间共享 JPA 实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73662710/

相关文章:

java - Spring 响应实体返回

spring-boot - 带有两个jar文件的Docker容器,按需运行而不是作为入口点

java - 为什么 Spring Data REST 包含 "duplicate"链接?

java - Id 必须可分配给 Serialized With LAZY @ManyToOne

java - Eclipse 未导入 com.google.api.client。进口?

java - 在 Maven 项目中获取 Tomcat 依赖项错误

java - Spring Data REST + JPA 从 OneToMany 集合中删除 [不是所有者端]

spring - 如何在 Spring Data 中使用投影覆盖 findById

java - 如何将 applicationContext.xml 中的对象转换为 java 注释

spring-boot - Spring boot 2.0.3.RELEASE,Spring data rest,应用报错,启动失败