简体   繁体   中英

How to share JPA entity across multiple spring boot applications

We would like to share the Employee across both applications exposed as micro services. But Employee has the JPA definition, how do we package this is as a separate jar which can be shared across multiple applications

Spring Boot "AppA" has following entity

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

}

Spring Boot "AppB" fetches Employee from "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.

If you really need to share them and do not want to copy and paste you can achieve that by packaging your shared entities and repos on a separate Spring project (without an Application.java) and declaring that project in your downstream services as maven/gradle dependency.

Let's say you've put the entities and repos in a separate library under the following packages: Under a package like my.common.lib.entities , my.common.lib.repos

You can make Spring discover them on your downstream services AppA and AppB by using @ComponentScan typically on your corresponding Spring Application classes:

AppA:

@ComponentScan(basePackages={"my.common.lib.entities", "my.common.lib.repos"})
@SpringBootApplication
ApplicationAppA {


}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM