Spring-Boot/JPA: Problem with packages and Entities

Issue

I have a Spring-Boot app with a component and a scheduled function.

package My.A;

@SpringBootApplication
@EnableScheduling
public class MyApp 
{
    public static void main (String args []) throws Exception
    {
      SpringApplication.run (MyApp.class, args);    
    }
}

The component:

package My.A;

@Component
public class MyComp
{   

  @Scheduled (fixedRate = 3000)
  public void foo ()
  {
    System.out.println ("foo");
  }
}

All is fine, I get every 3s the printout of "foo".

Now I want to add JPA. It is not the 1st time I use JPA.

But it is the 1st time I have the entity in another package (My.B).

package My.B;

@Entity
@SequenceGenerator (name = "seq", initialValue = 1)
public class MyRecord
{ 
....

I added a Repository in App to access the DB.

package My.A;

public interface MyRecordRepo extends CrudRepository <MyRecord, Long> 
{
}

And I add annotations to let MyApp find MyRecord of My.B.

package My.A;

@SpringBootApplication
@EnableScheduling
@EnableJpaRepositories ("My.B.*")                    // NEW
@ComponentScan (basePackages = { "My.B.*" })         // NEW

public class WebApplication 
{
...

Without that MyApp would throw an exception at start that the Entity is not found.
With the annotation it compiles and started fine.

But now my scheduled function foo does not get fired.
I tried to add My.A.* into ComponentScan but did not work.

@ComponentScan (basePackages = { "My.B.*", "My.A.*" })   

Think MyApp does not find its own component now.

How can I get my scheudled function back AND also have JPA with the class outside of my primary package?

Solution

Add @EntityScan("My.B") to your configuration.

When you use @ComponentScan it disables Spring Boot auto-configuration scanning and you have to specify all the used packages manually.

Also, you don’t need @EnableJpaRepositories – Spring Boot does this automatically if it finds Spring Data JPA on the classpath.

Answered By – dekkard

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published