javaspring-boot

Springboot @EntityScan not working


I have a Springboot application and my entity model is separated from my main application included as dependency.

my Application.java is located in this package com.a.b.c

@SpringBootApplication
@EntityScan("com.a.b")
public class Applciation
{
    public static void main(String args[])
    {
         SpringApplication.run(Applciation.class, args);
    }
}

and my entity model is located in another project inside this package com.a.b

But I'm getting an error: Caused by: java.lang.IllegalArgumentException: Not a managed type: class


Solution

  • I can relate to you. I have spent countless hours regarding this.

    I'll divide your question to 3 parts (I will use "entity-project" and "spring-project" to refer to the project containing entity classes and main project trying to incorporate entity classes) :

    Part 1 of 3: Making sure your entity classes are exposed in entity-project.

    Create a Config at the root of entity-project

    package com.a.b
    
    @Configuration
    @Import ({Entity1.class, Entity1Repo.class, Entity1Key.class, 
      Entity2.class, ... })
    class EntityConfig {}
    

    Part 2 of 3: Making sure your entity classes are in the classpath of spring-project.

    Since you are using SpringBoot, I'm sure you are using maven (or Gradle).

    Anyway, make sure you maven install the entity-project with entity classes:

    cd /path/to/entity-project/
    mvn install -DskipTests 
    

    In spring-project's maven file, include to the entity-project.

    Part 3 of 3: Use the EntityScan annotation.

    It is just my taste, but I prefer using basePackageClasses instead of basePackage.

    @SpringBootApplication
    @EntityScan(basePackageClasses = {Entity1.class}) 
    // use basePackageClasses to avoid type errors
    @Import({com.a.b.EntityConfig.class}) // this is what you are missing
    public class Applciation
    {
        public static void main(String args[])
        {
             SpringApplication.run(Applciation.class, args);
        }
    }
    

    Viola!