Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Including only individual entities in Spring Boot JPA Test

I am trying to test jpa queries in a separate projects entities by quickly kicking off a spring boot project to generate a platform to insert data into a H2 database, run queries against it, and validate the results of these queries.

Because the separate project has a large entity base, I'd like to selectively pick out the entities that I want to per test.

I've tried to use the @EntityScan annotation for this, but it seems designed to pull entire packages, even if you just specify a class.

This strikes me as something that there must be a solution for, but I have so far been unable to find it.

like image 326
Stephen Erdman Avatar asked Oct 31 '25 11:10

Stephen Erdman


2 Answers

The thing is that when you set up a test class with a Spring context, that context exists for all the tests in that class, unless you use @DirtiesContext or some other trick to make it rebuild itself.

@EntityScan(basePackageClasses = MyEntity.class)

The code above doesn't tell Spring to use MyEntity, it tells it to start searching for entities in the package that MyEntity exists in. It also does so recursively, so if you have for instance:

com.example.entities.MyEntity
com.example.entities.subpackage.MyOtherEntity

It would pick up both MyEntity and MyOtherEntity. If, however, you wrote your EntityScan like this:

@EntityScan(basePackageClasses = MyOtherEntity.class)

Then MyEntity would not be found.

With that in mind, the only suggestion I have for you is perhaps to group your large number of entities into multiple smaller subpackages to make it easier to load, if loading all of them at once is indeed a showstopper for you.

like image 187
Thomas Kåsene Avatar answered Nov 03 '25 03:11

Thomas Kåsene


So, I came up with a solution using Hibernate specific code. The Hibernate SessionFactoryBeans have an addAnnotatedClass method, so if you create a LocalSessionFactoryBean bean in your configuration file, you can just pass in the individual classes that you want. If you get a little creative, you can add the classes you want to test (I also have a DependencyGrapher that lets me know all the entity classes I need to pull in) as @TestPropertySource's in your test class and reference those values in the set up code.

It's actually pretty easy if you are using Hibernate, which, unfortunately, I am not able to do. I'm constrained to use EclipseLink, which just doesn't seem to offer this out of the box. I think I have a lead with Spring's PersistenceUnitPostProcessor though.

like image 44
Stephen Erdman Avatar answered Nov 03 '25 01:11

Stephen Erdman



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!