17

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?

5
  • You can remove/comment the @Entity annotation untill your entity is complete. Than it won't be picked up by persistence provider. May 8, 2013 at 13:42
  • 1
    Isn't it possible to scan just some particular entities that I want to test with? May 8, 2013 at 15:33
  • You can also remove packagesToScan option, create persistence.xml and list entities here. I still don't understand your motivation to exclude some entities - you can easily remove @Entity annotations if you are in the middle of the development and your entity isn't complete, or am I missing something? May 8, 2013 at 17:42
  • 1
    Have you ever find a solution to ignore some entities within packagestoscan ?
    – nilgun
    Nov 22, 2015 at 16:31
  • @nilgun No, I haven't. Nov 23, 2015 at 5:51

4 Answers 4

12

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.

0
6

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");
        }
    });
3

I found a solution to use setPackagesToScan and then remove unwanted packages. It turns out that persistenceUnit.getManagedClassNames() in PersistenceUnitPostProcessor returns a regular ArrayList which can be manipulated.

em.setPersistenceUnitPostProcessors(new PersistenceUnitPostProcessor() {
    @Override
    public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo persistenceUnit) {
        List<String> managedClassNames = persistenceUnit.getManagedClassNames();
        managedClassNames.removeIf(fullClassName -> fullClassName.startsWith("com.example.twodatasources.product"));
    }
});

In my case the shown persistanceUnit is responsible for all entities but the ones in com.example.twodatasources.product package. The other one in responsible only for com.example.twodatasources.product.

The code above is for the hibernate part. It's worth to mention that the spring part should also be filtered. This can be achieved by adding a ComponentScan.Filter to @EnableJpaRepositories as shown below:

@Configuration
@PropertySource({ "classpath:application.yml" })
@EnableJpaRepositories(
    basePackages = "com.example.twodatasources",
    excludeFilters = {@ComponentScan.Filter(type = FilterType.REGEX, pattern = "com\\.example\\.twodatasources\\.product\\..*")},
    entityManagerFactoryRef = "userEntityManager",
    transactionManagerRef = "userTransactionManager"
)
0

I also used entityTypeFilters to ignore some classes while scanning PackagesToScan

but as I found out setting entityTypeFilters via

<property name="entityTypeFilters" ref="packagesToScanIncludeRegexPattern">

clears existing default filters which are(according documentation):

Specify custom type filters for Spring-based scanning for entity classes. Default is to search all specified packages for classes annotated with @javax.persistence.Entity, @javax.persistence.Embeddable or @javax.persistence.MappedSuperclass.

As I checked in debug this is resulted in having all class packages being scanned by spring which match packagesToScan condition except packagesToScanIncludeRegexPattern regex. This has impact on startup time.

As workaround I implemented custom filter with filters as by default puls regexp filter:

public class RegexPatternEntitiesTypeFilter extends AbstractClassTestingTypeFilter {

private final Set<String> entityPackageRegistry;
private final Pattern pattern = Pattern.compile("^(?!my.company.package.exclude).*");

public RegexPatternEntitiesTypeFilter() {
    entityPackageRegistry = ImmutableSet.of(Entity.class.getName(), Embeddable.class.getName(),
        MappedSuperclass.class.getName());
}

@Override
protected boolean match(ClassMetadata metadata) {
    boolean result = true;
    if (metadata instanceof AnnotationMetadataReadingVisitor) {
        Set<String> annotationTypes = ((AnnotationMetadataReadingVisitor) metadata).getAnnotationTypes();
        result = !Sets.intersection(entityPackageRegistry, annotationTypes).isEmpty();
    }
    boolean matches = this.pattern.matcher(metadata.getClassName()).matches();
    return result && matches;
}

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.