Search code examples
spring-bootjpaspring-data-jpa

@EnableJpaRepositories/@EntityScan annotations mandatory in spring data jpa configuration setup?


I was going through this tutorial where the instructor was configuring Spring Data JPA. He had created the Entity classes and Repository interfaces and then added the @EnableJpaRepositories and @EntityScan annotations on the main application as follows:

@SpringBootApplication
@ComponentScan({"com.test.controller", "com.test.services"})
@EnableJpaRepositories("com.test.repository")
@EntityScan("com.test.entity")
public class MainApplication{
    public static void main(String args[]){
         SpringApplication.run(MainApplication.class, args[]);
    }
}

I was creating the same project on the side, which had the same Entity classes and Repository interfaces but my main application didn't have these annotations. Instead, I added only @SpringBootApplication. Despite the absence of the said annotations, I found the code to be working well and fetching data from the db without issues. So my question is, what is the advantage of adding these annotations to the code ? Is it just for specifying the package where you can find the corresponding files, or are there any other advantages ?


Solution

  • By default, Spring searches for entities and repos in package where you placed your main class (and below this package). For example having these packages:

    java
    -com
    ---pack1
    -----AnyEntity.java
    ---pack2
    -----Main.java

    Spring won't be able to find AnyEntity automatically. In this situation you need to specify where the entity is using @EntityScan. When it comes to repositories, you deal with it similarly using @EnableJpaRepositories.