icordoba
icordoba

Reputation: 1899

Packaging JPA entities in a jar inside a Spring Boot application

I am refactoring a JEE REST (using JAX-RS 2.0) application as a Spring Boot application. My old app is packaged in a .war and has a jar file with entities and the persistence.xml configuration file for JPA. This jar is copied into WEB-INF/lib directory. I know Spring JPA works a different way and I don't use persistence.xml now but I wonder if I can package my JPA entity classes in a jar and include them in my Spring Boot apps just like I am doing now. This way I can easily reuse that jar in different Spring Boot Applications.

Upvotes: 2

Views: 3721

Answers (3)

Mark Bramnik
Mark Bramnik

Reputation: 42501

Spring Boot doesn't really care whether the JPA entities are packages as a separate jar or included into the application. Its a runtime framework and in runtime classes can be loaded from the jar (it should reside in BOOT-INF/lib or 'directly' from the *.class files in the spring boot artifact.

Now there is a rule in spring boot, that says that it will scan for beans (including entities) only in the package where your "main" class resides or under it. This is done in order to avoid long process of analysis of, say, third-party classes that you might use. These third-party classes are usually not spring aware at all, at certainly do not contain any spring beans.

Example:

Say, you place your "main" class (the one annotated with @SpringBootApplication) in the package: com.mycompany.myapp

In this case, the following packages will be scanned (just a couple of examples):

  • com.mycompany.myapp
  • com.mycompany.myapp.web
  • com.mycompany.myapp.services.bl
  • com.mycompany.myapp.whatever.doesnt.matter ...

The following packages won't be scanned however (again, examples, not the full list):

  • com.mycompany
  • com.anothercompany
  • org.hibernate

If you want to to "alter" this default rule and place the entities in the package that doesn't adhere this convention, for example com.mycompany.jpa.entities then you should indeed use @EntityScan annotation as our colleagues have already suggested.

You can read about this topic here. You might also need to get familiar with @EnableJpaRepositories if you're using spring data but, while related, its a different topic.

Upvotes: 2

Gustavo Braz
Gustavo Braz

Reputation: 1

In my case I had this problem, and after importing the library in the application's pom.xml, in the SpringBoot Project Main class, insert an @EntityScan annotation with the first package and *. Like this: @EntityScan ("br.*")

Upvotes: 0

Plog
Plog

Reputation: 9622

I'm pretty certain you can do this since I have done the same on one of my projects very recently. The only thing you need to do is make sure that you add an @EntityScan annotation on your main Spring Boot config class with the base package of your entities in the JAR.

@EntityScan("my.external.jar.entity.package")

Upvotes: 3

Related Questions