Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How just scan a concrete JPA entity but not all entities bellow the same package with spring-boot?

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;
    //...
}
like image 394
RJ.Hwang Avatar asked Oct 17 '25 17:10

RJ.Hwang


1 Answers

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.

like image 131
RJ.Hwang Avatar answered Oct 19 '25 08:10

RJ.Hwang



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!