String boot filter Entity class on @entityscan

77 views Asked by At

I've a micro-services architecture system using spring boot. The service A, has its model classes (A1, A2, A3) SOME OF WHICH, should be reusable by services B, C, D... Each service (B, C, D) has its own local database and doesn't need to keep track of all Service A entities, just the a few ones.

All Service A, model classes are anottated @Entity

How can I achieve this behavior using spring-boot hibernate.

Trying to make an specific example:
I've a jar, containing only @Entityclasses, i'm interested in importing a few of this classes in my project and generating the respective tables for that, but completing ignoring most of the classes

I've @EntityScan(basePackageClasses = {ServiceAModel1.class, ServiceAModel2.class}) but it scan the whole package and inevitably adds all model classes to entitymanager and so fails if the local service doesn't create tables for any of this classes

how can i approach this problem?

2

There are 2 answers

1
elisman On

If you share something between services, you should create a package with the common entities and release and manage them separately.

So create a common-entities package that includes all entities you want to share and import it into services A, B, C and D. This way only the entities you want to share are exposed.

0
Panagiotis Bougioukos On

Currently there isn't any feature with which you can filter for registration specific entities which coexist under the same package. This limitation has been for years.

In some days (15/02/24) the 6.1.4 version of spring-core would be rolled out and as it currently seems this new feature (Provide more control over JPA entities scanning) is going to be included in this version.

So if the release scope stays as it currently is, from 6.1.4 you would be able to register only the specific entities you want by configuring your own DefaultPersistenceUnitManager.

You could register it in your configuration context as described bellow

@Bean
public DefaultPersistenceUnitManager persistenceUnitManager(DataSource dataSource) {
    DefaultPersistenceUnitManager defaultPersistenceUnitManager = new DefaultPersistenceUnitManager();
    defaultPersistenceUnitManager.setDefaultDataSource(dataSource);

     defaultPersistenceUnitManager.setPackagesToScan("com.package1", "com.package2");
     defaultPersistenceUnitManager.setManagedClassNameFilter(className -> className.startsWith("MyEntityClass1") || className.startsWith("MyEntityClass2"));
    return defaultPersistenceUnitManager;
}

This way all entities included in com.package1 and com.package2 would be scanned but the filter would exclude all others scanned entities in these packages and register only MyEntityClass1.java and MyEntityClass2.java.