In a Spring Data JPA environment, you may want to retrieve the domain type of the repositories defined in your application. This tutorial will show two ways to retrieve Spring JPA repository domain type.
The two following solutions require Spring data commons. Make sure you have it in classpath.
Using Repositories
Spring data commons provides the class Repositories to handle JPA repositories. You can use it to retrieve the domain type of each repository as below :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import java.util.Iterator; import org.springframework.beans.factory.ListableBeanFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.context.event.EventListener; import org.springframework.data.repository.Repository; import org.springframework.data.repository.support.Repositories; import org.springframework.stereotype.Component; @Component public class ContextRefreshedEventListner { @Autowired private ListableBeanFactory listableBeanFactory; @SuppressWarnings("rawtypes") @EventListener public void handleContextRefresh(ContextRefreshedEvent event) { Repositories repositories = new Repositories(listableBeanFactory); Iterator<Class<?>> it = repositories.iterator(); while (it.hasNext()) { Class<?> domainClass = it.next(); Repository repository = (Repository) repositories.getRepositoryFor(domainClass); System.out.println("The domain of the repository [" + repository + "] is : " + domainClass); } } } |
Using DefaultRepositoryMetadata
Spring data commons provides also DefaultRepositoryMetadata to retrieve repositories information. Below the usage :
1 2 |
DefaultRepositoryMetadata drm = new DefaultRepositoryMetadata(BookRepository.class); Class<?> domainType = drm.getDomainType(); |
An example of usage is available on Github. Download the source