问题
I've a package (say packagesToScan
) containing Classes that I wish to persist annotated with @Entity
.
While defining ApplicationContext
configuration, I've done as follows.
@Configuration
@EnableJpaRepositories("packagesToScan")
@EnableTransactionManagement
@PropertySource("server/jdbc.properties")
@ComponentScan("packagesToScan")
public class JpaContext {
...
// Other configurations
....
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(this.dataSource());
emf.setJpaVendorAdapter(this.jpaVendorAdapter());
emf.setPackagesToScan("packagesToScan");
emf.setJpaProperties(this.hibernateProperties());
return emf;
}
While developing, I've some classes within packagesToScan
which doesn't satisfy requirements for persistence (like no primary keys etc) and due to this I'm not allowed to run test because of ApplicationContext
setup failure.
Now,
Is there any way that I can scan just some selected classes or ignore some classes within packagesToScan
?
回答1:
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.
回答2:
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");
}
});
来源:https://stackoverflow.com/questions/16293437/ignore-some-classes-while-scanning-packagestoscan