如何过滤LocalContainerEntityManagerFactoryBean扫描的entites?

时间:2015-07-24 07:21:22

标签: java spring jpa spring-data spring-data-jpa

我使用Spring Boot,Spring Data JPA和Hibernate。

我需要通过自定义注释过滤由EntityManager管理的实体。 LocalContainerEntityManagerFactoryBean允许设置扫描的包列表,但过滤器似乎在DefaultPersistenceUnitManager中进行了硬编码。

否则LocalSessionFactoryBuilder(特定于Hibernate)具有此功能(方法setEntityTypeFilters),但不能与需要EntityManagerFactory的Spring Data JPA存储库一起使用。

如何将实体过滤应用于LocalContainerEntityManagerFactoryBean

2 个答案:

答案 0 :(得分:2)

我遇到了类似的问题:我想"排除"某些实体仍使用LocalContainerEntityManagerFactoryBean提供的包扫描。就我而言,我想使用spring使用的@Profile(...)注释,因为只有在特定的配置文件处于活动状态时才需要某些实体。 我通过实现PersistenceUnitPostProcessor来解决它,它删除了扫描程序添加的类。它可能不是最优雅的解决方案,但它有效(Spring 4.1.2)。

public class ProfileAwarePersistenceUnitPostProcessor implements PersistenceUnitPostProcessor {

    @Autowired
    Environment environment;

    /**
     * Post process the persistence unit and remove Entity classes that require a specific spring profile
     * if profile is not active.
     * 
     * @param pui The persistence unit that was put together so far.
     * @see org.springframework.orm.jpa.persistenceunit.PersistenceUnitPostProcessor#postProcessPersistenceUnitInfo(org.springframework.orm.jpa.persistenceunit.MutablePersistenceUnitInfo)
     */
    @Override
    public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo pui) {
        // Check for null to be sure.
        if (pui.getManagedClassNames() != null) {
            Iterator<String> iterator = pui.getManagedClassNames().iterator();
            while (iterator.hasNext()) {
                String className = iterator.next();
                try {
                    Class<?> entityClass = Class.forName(className);
                    Profile profileAnnotation = entityClass.getAnnotation(Profile.class);
                    if (profileAnnotation != null) {
                        String[] requiredProfiles = profileAnnotation.value();
                        if (!environment.acceptsProfiles(requiredProfiles)) {
                            Logging.debug("Removing class " + className + " from persistence unit since none of the required profiles is active "
                                    + StringUtils.join(", ", requiredProfiles));
                            iterator.remove();
                        }
                    }
                } catch (ClassNotFoundException e) {
                    // Something must have gone wrong during scanning if class is suddenly not found anymore.
                    Logging.warn("Class " + className + " not found  while post processing persistence unit.", e);
                }
            }
        }
    }
}

可以使用任何其他注释代替Profile。

答案 1 :(得分:0)

使用Spring Boot,只需使用reference documentation中描述的@EntityScan

如果 - 如此问题的评论中所述 - 您需要使用多个数据源,请查看corresponding project in the Spring Data example repository