I'm sharing my solution which is based on other answer.
In my case which configures multiple databases, I don't why but, I need to autowire instances of EntityManagerFactory
.
@Db1 @Autowire
EntityManagerFactory entityManagerFactoryDb1;
@Db2 @Autowire
EntityManagerFactory entityManagerFactoryDb2;
Now all I need is a method streaming all entity classes gathered from all injected persistence units.
(Maybe, checking the existence of @Entity
annotation or a custom annotation , say @EntityRestExposeId
, can be applied.)
private void forEachEntityClass(final Consumer<? super Class<?>> consumer) {
Arrays.stream(DataRestConfiguration.class.getDeclaredFields())
.filter(f -> {
final int modifiers = f.getModifiers();
return !Modifier.isStatic(modifiers);
})
.filter(f -> EntityManagerFactory.class.isAssignableFrom(f.getType()))
.map(f -> {
f.setAccessible(true);
try {
return (EntityManagerFactory) f.get(this);
} catch (final ReflectiveOperationException roe) {
throw new RuntimeException(roe);
}
})
.flatMap(emf -> emf.getMetamodel().getEntities().stream().map(EntityType::getJavaType))
.forEach(consumer);
}
Calling the exposeIdFor
method is straightforward.
@Configuration
class DataRestConfiguration {
@Bean
public RepositoryRestConfigurer repositoryRestConfigurer() {
return RepositoryRestConfigurer.withConfig((configuration, registry) -> {
forEachEntityClass(configuration::exposeIdsFor);
// ...
});
}
private void forEachEntityClass(final Consumer<? super Class<?>> consumer) {
// ...
}
@Db1 @Autowired
EntityManagerFactory entityManagerFactoryDb1;
@Db2 @Autowired
EntityManagerFactory entityManagerFactoryDb2;
@Db3 @Autowired
EntityManagerFactory entityManagerFactoryDb3;
}