Ignore some classes while scanning PackagesToScan

喜夏-厌秋 提交于 2019-12-01 15:22:01
nilgun

I have been trying to solve the same problem and finally got a solution as below:

<bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="myDataSource"/>
    <property name="packagesToScan" value="com.mycompany.bean"/>
    <property name="entityTypeFilters" ref="packagesToScanIncludeRegexPattern">
    </property>
    <property name="hibernateProperties">
        // ...
    </property>
</bean>

<bean id="packagesToScanIncludeRegexPattern" class="org.springframework.core.type.filter.RegexPatternTypeFilter" >
    <constructor-arg index="0" value="^(?!com.mycompany.bean.Test).*"/>
</bean>

I realized that there is a setEntityTypeFilters function on the LocalSessionFactoryBean class which can be used to filter which classes to be included. In this example I used RegexPatternTypeFilter but there are other types of filters as well.

Also note that the filters work with include semantics. In order to convert to exclude semantics I had to use negative lookahead in the regex.

This example shows the xml configuration but it should be trivial to convert to java based configuration.

I stumbled upon a simmilar problem. I needed to add some but not all entities from a package. Here is how I did it:

// add all entities from some package
localContainerEntityManagerFactoryBean.setPackagesToScan("com.companyname.model");
// add only required enitites from a libray
localContainerEntityManagerFactoryBean.setPersistenceUnitPostProcessors(new PersistenceUnitPostProcessor() {
        @Override
        public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo persistenceUnit) {
            persistenceUnit.addManagedClassName("com.companyname.common.model.SomeEntityName");
        }
    });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!