4

I have multiple JPA entities bellow the same package, such as my.package.po.EntityA and my.package.po.EntityB. Use bellow code will auto scan both EntityA and EntityB, but I just want to scan EntityA. How can I do this?

package my.package.dao;
...
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {EntityADaoJpaImpl.class})
@DataJpaTest
@EntityScan(basePackageClasses = {EntityA.class})
public class EntityADaoJpaImplTest {
    @Inject
    private TestEntityManager entityManager;
    @Inject
    private EntityADaoJpaImpl dao;
    //...
}
RJ.Hwang
  • 1,683
  • 14
  • 24
  • Seems that your problem was fixed here: https://stackoverflow.com/questions/16293437/ignore-some-classes-while-scanning-packagestoscan – nikita_pavlenko Jun 09 '17 at 17:10
  • That need to write more complicated code. Does have someway like @EntityScan(classes = EntityA.class) ? – RJ.Hwang Jun 11 '17 at 04:13

1 Answers1

3

After some research, specially follow 'ignore-some-classes-while-scanning-packagestoscan' idea:

// add only required enitites from a libray
localContainerEntityManagerFactoryBean.setPersistenceUnitPostProcessors(new PersistenceUnitPostProcessor() {
  @Override
  public void postProcessPersistenceUnitInfo(MutablePersistenceUnitInfo persistenceUnit) {
    persistenceUnit.addManagedClassName("my.package.po.EntityA");
  }
});

I make some custom code encapsulation to simplify my unit-test:

package my.package.dao;
import tech.simter.test.jpa.EntityScan;
import tech.simter.test.jpa.JpaTestConfiguration;
...
@RunWith(SpringRunner.class)
@ContextConfiguration(classes = {EntityADaoJpaImpl.class, JpaTestConfiguration.class})
@DataJpaTest
@EntityScan({EntityA.class})
public class EntityADaoJpaImplTest {
  @Inject
  private TestEntityManager entityManager;
  @Inject
  private EntityADaoJpaImpl dao;
  //...
}

It totally resolve my problem. And the code encapsulation idea comes from the implementation of spring-boot-autoconfigure org.springframework.boot.autoconfigure.domain.EntityScan class.

My source code hosts here. It is on github.

RJ.Hwang
  • 1,683
  • 14
  • 24
  • Really useful solution. The only drawback is the selected class must not have any associations to other entity classes. Otherwise the entity manager tries to load all associations anyway, which fails. – Tomáš Záluský Mar 27 '19 at 16:53