Home > Enterprise >  How to share JPA entity across multiple spring boot applications
How to share JPA entity across multiple spring boot applications

Time:09-11

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();

CodePudding user response:

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.

CodePudding user response:

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 {


}
  • Related