Spring boot - Not a managed type
Asked Answered
M

33

281

I use Spring boot+JPA and having a problem while starting the service.

Caused by: java.lang.IllegalArgumentException: Not an managed type: class com.nervytech.dialer.domain.PhoneSettings
    at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:219)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:68)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getMetadata(JpaEntityInformationSupport.java:65)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:145)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:89)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:69)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:177)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.initAndReturn(RepositoryFactoryBeanSupport.java:239)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.afterPropertiesSet(RepositoryFactoryBeanSupport.java:225)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean.afterPropertiesSet(JpaRepositoryFactoryBean.java:92)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1625)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1562)

Here is the Application.java file,

@Configuration
@ComponentScan
@EnableAutoConfiguration(exclude = { DataSourceAutoConfiguration.class })
@SpringBootApplication
public class DialerApplication {

    public static void main(String[] args) {
        SpringApplication.run(DialerApplication.class, args);
    }
}

I use UCp for connection pooling and the DataSource configuration is below,

@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableAutoConfiguration
@EnableJpaRepositories(entityManagerFactoryRef = "dialerEntityManagerFactory", transactionManagerRef = "dialerTransactionManager", basePackages = { "com.nervy.dialer.spring.jpa.repository" })
public class ApplicationDataSource {

    /** The Constant LOGGER. */
    private static final Logger LOGGER = LoggerFactory
            .getLogger(ApplicationDataSource.class);

    /** The Constant TEST_SQL. */
    private static final String TEST_SQL = "select 1 from dual";

    /** The pooled data source. */
    private PoolDataSource pooledDataSource;

UserDetailsService Implementation,

@Service("userDetailsService")
@SessionAttributes("user")
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserService userService;

Service layer implementation,

@Service
public class PhoneSettingsServiceImpl implements PhoneSettingsService {

}

The repository class,

@Repository
public interface PhoneSettingsRepository extends JpaRepository<PhoneSettings, Long> {

}

Entity class,

@Entity
@Table(name = "phone_settings", catalog = "dialer")
public class PhoneSettings implements java.io.Serializable {

WebSecurityConfig class,

@Configuration
@EnableWebMvcSecurity
@ComponentScan
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    /**
     * Instantiates a new web security config.
     */
    public WebSecurityConfig() {

        super();
    }

    /**
     * {@inheritDoc}
     * @see org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#configure(org.springframework.security.config.annotation.web.builders.HttpSecurity)
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.authorizeRequests()
            .antMatchers("/login", "/logoffUser", "/sessionExpired", "/error", "/unauth", "/redirect", "*support*").permitAll()
            .anyRequest().authenticated().and().rememberMe().and().httpBasic()
            .and()
            .csrf()
            .disable().logout().deleteCookies("JSESSIONID").logoutSuccessUrl("/logoff").invalidateHttpSession(true);
    }


    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

      auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

}

The packages are as follows,

  1. Application class is in - com.nervy.dialer
  2. Datasource class is in - com.nervy.dialer.common
  3. Entity classes are in - com.nervy.dialer.domain
  4. Service classes are in - com.nervy.dialer.domain.service.impl
  5. Controllers are in - com.nervy.dialer.spring.controller
  6. Repository classes are in - com.nervy.dialer.spring.jpa.repository
  7. WebSecurityConfig is in - com.nervy.dialer.spring.security

Thanks

Mnemonics answered 22/2, 2015 at 22:28 Comment(1)
I believe you'll still need to tell Hibernate to scan the package for your entity object.Colchis
N
69

I think replacing @ComponentScan with @ComponentScan("com.nervy.dialer.domain") will work.

Edit :

I have added a sample application to demonstrate how to set up a pooled datasource connection with BoneCP.

The application has the same structure with yours. I hope this will help you to resolve your configuration problems

Norine answered 23/2, 2015 at 7:21 Comment(5)
If I add @ComponentScan("com.nervy.dialer.domain"), I am getting datasource not fond exception since its in a different package. Added that package also like @ComponentScan({"com.nervy.dialer.domain","com.nervy.dialer.common"}). Now gettting the same old error.Mnemonics
I have added a sample application to demonstrate how to set up a pooled datasource connection with BoneCP. github.com/azizunsal/SpringBootBoneCPPooledDataSource The application has the same structure with yours. I hope this will help you to resolve your configuration problems.Norine
You did the magic. It works fine. Thanks for your help. I had the following annotation in the datasource. @EnableJpaRepositories(entityManagerFactoryRef = "dialerEntityManagerFactory", transactionManagerRef = "dialerTransactionManager", basePackages = { "com.nervytech.dialer.repository"}). After removing this and just adding @EnableJpsRespository in DialerApplication, it started working fine.Mnemonics
I have the same problem. Spring boot doesn't recognize my Entity(@DynamicUpdate from hibernate 4+ version). I've tried with adding my model package in ComponentScan or EntityScan and i gets same error. My Annotations in Application class are: SpringBootApplication ComponentScan(basePackages = {"com.example.controllers", "com.example.services", "com.example.models"}) EnableAutoConfiguration @Configuration @EnableJpaRepositories(basePackages = {"com.example.dao", "com.example.models"})Pedaias
The same scenario we used Hibernated as a JPA provider. As after tried all these solution still the issue exists. Added this configuration in my application configuration file resolved the issue for me. hibernate.annotation.packages.to.scan = ${myEntityPackage}Colored
B
201

Try adding All the following, In my application it is working fine with tomcat

 @EnableJpaRepositories("my.package.base.*")
 @ComponentScan(basePackages = { "my.package.base.*" })
 @EntityScan("my.package.base.*")   

I am using spring boot, and when i am using embedded tomcat it was working fine with out @EntityScan("my.package.base.*") but when I tried to deploy the app to an external tomcat I got not a managed type error for my entity.

Extra read:

@ComponentScan is used for scanning all your components those are marked as @Controller, @Service, @Repository, @Component etc…

where as @EntityScan is used to scan all your Entities those are marked @Entity for any configured JPA in your application.

Banderillero answered 19/1, 2016 at 18:59 Comment(6)
Ditto! And for me to get the above to work for the POC i'm doing, I just added all of those to my spring boot applications annotations, and use com.* as the matcher - which seemed to resolve my case easily for all the classes i had from 2 different com.* namespaces! @EnableJpaRepositories("com.*") @ComponentScan(basePackages = { "com.*" }) @EntityScan("com.*")Jacey
Worked perfectly for me . It seems @EntityScan is requiredFoldboat
It seems that .* is not required, as it recursively goes inside scanning eveything inside base packageCissy
Should be without the asterisk *. It will not work with it.Mislead
With asterick * it is not working.Euxenite
Thanks for differentiating the ComponentScan and EntityScan annotations. Helpful.Zeigler
D
169

Configure the location of entities using @EntityScan in Spring Boot entry point class.

Update on Sept 2016: For Spring Boot 1.4+:
use org.springframework.boot.autoconfigure.domain.EntityScan
instead of org.springframework.boot.orm.jpa.EntityScan, as ...boot.orm.jpa.EntityScan is deprecated as of Spring Boot 1.4

Danille answered 23/2, 2015 at 22:14 Comment(4)
This option also does not help. I guess, I am missing something else in my configuration.Mnemonics
Doesn't help in my case too.Pedaias
It did work for me but it's a deprecated annotation.Jason
Thanks Juan, I have updated the answer with the current version of Entity Scan.Danille
P
84

jpa entity is not a managed type

Root cause if experienced in recent versions of Sp:

In the recent version of Springboot and JDK, this error is a result of the "Javax" namespace used in Java EE being replaced with the "Jakarta" namespace in Jakarta EE.

Fix

Therefore, in a newer version of Spring Version and JDK. e.g. Spring 6+ and JDK 17+, you would now need to replace javax.persistence.Entity when with jakarta.persistence.Entity to resolve the jpa entity is not a managed type error

Further context

@SakshamGupta. The root cause is:

In 2017, Oracle (acquired Java EE) decided to transfer the ownership, maintenance, and future development of Java EE to the Eclipse Foundation. This transfer led to the creation of Jakarta EE.

As part of this transition, the package naming conventions also changed. The "Javax" namespace used in Java EE was replaced with the "Jakarta" namespace in Jakarta EE.

Hence newer versions of Java and Spring Boot have adopted Jakarta EE from JDK17 and Spring Boot v3, that is. Consequently, you needed to switch to jakarta.persistence.Entity. This change reflects the shift from Java EE to Jakarta EE and the updated package naming conventions.

Here is additional material:

Petrie answered 13/12, 2022 at 15:50 Comment(6)
This did the trick for me because I was basing my code in code from previous versions of SpringBoot 3.x.x, i'm so grateful for this answer, thanks!Paganism
For anyone who stumbles upon this. If you are following the SpringBoot tutorial and end up with this error, javax persistence library has been jakarta persistence, which will solve the issue. I am very new to java, so this caught me off-guard.Forcible
jar depenency used javax.persistence. Didn't want to go through and update all the annotations. Using older (2.5.5) version of Spring Boot rather than 3.x solved it for usConsummation
This solved my problem. Although i would like to understand how did u find this out that swapping javax with jakarta will solve this issue. Any sources maybe?Tubb
Adding to this, from a reddit post that helped me - 1. Remove the persistence-api dependency from pom.xml. 2. Rename javax to jakarta in the entity/model class. Source: reddit.com/r/SpringBoot/comments/17ffwep/not_a_managed_type_error/Peasecod
This is the right answer for simple spring boot applicationsAnnounce
N
69

I think replacing @ComponentScan with @ComponentScan("com.nervy.dialer.domain") will work.

Edit :

I have added a sample application to demonstrate how to set up a pooled datasource connection with BoneCP.

The application has the same structure with yours. I hope this will help you to resolve your configuration problems

Norine answered 23/2, 2015 at 7:21 Comment(5)
If I add @ComponentScan("com.nervy.dialer.domain"), I am getting datasource not fond exception since its in a different package. Added that package also like @ComponentScan({"com.nervy.dialer.domain","com.nervy.dialer.common"}). Now gettting the same old error.Mnemonics
I have added a sample application to demonstrate how to set up a pooled datasource connection with BoneCP. github.com/azizunsal/SpringBootBoneCPPooledDataSource The application has the same structure with yours. I hope this will help you to resolve your configuration problems.Norine
You did the magic. It works fine. Thanks for your help. I had the following annotation in the datasource. @EnableJpaRepositories(entityManagerFactoryRef = "dialerEntityManagerFactory", transactionManagerRef = "dialerTransactionManager", basePackages = { "com.nervytech.dialer.repository"}). After removing this and just adding @EnableJpsRespository in DialerApplication, it started working fine.Mnemonics
I have the same problem. Spring boot doesn't recognize my Entity(@DynamicUpdate from hibernate 4+ version). I've tried with adding my model package in ComponentScan or EntityScan and i gets same error. My Annotations in Application class are: SpringBootApplication ComponentScan(basePackages = {"com.example.controllers", "com.example.services", "com.example.models"}) EnableAutoConfiguration @Configuration @EnableJpaRepositories(basePackages = {"com.example.dao", "com.example.models"})Pedaias
The same scenario we used Hibernated as a JPA provider. As after tried all these solution still the issue exists. Added this configuration in my application configuration file resolved the issue for me. hibernate.annotation.packages.to.scan = ${myEntityPackage}Colored
P
60

If you configure your own EntityManagerFactory Bean or if you have copy-pasted such a persistence configuration from another project, you must set or adapt the package in EntityManagerFactory's configuration:

@Bean
public EntityManagerFactory entityManagerFactory() throws PropertyVetoException {
    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    vendorAdapter.setGenerateDdl(true);
    LocalContainerEntityManagerFactoryBean factory;
    factory = new LocalContainerEntityManagerFactoryBean();
    factory.setPackagesToScan("!!!!!!package.path.to.entities!!!!!");
    //...
}

Be careful of the "multiple" needs, you need a String array as the argument passed to setPackagesToScan (and NOT a comma-separated-single-string value). Below illustrates the issue.

    String[] packagesArray = "com.mypackage1,com.mypackage2".split(",");
    em.setPackagesToScan(packagesArray);
Pout answered 19/2, 2019 at 10:56 Comment(5)
Note, if you have to pass in multiple values for setPackagesToScan, you pass in a string [] array, and NOT a comma separated list of package names.Donniedonnish
Indeed "factory.setPackagesToScan is the key solution, you have to add your missing model package name here.Sundried
Thank you for the multiple needs section -> The XML configuration accepts comma separated string, but for some reason Java based does not.Gardell
Clear answer and perfect solution to my issue. Upvoted! Thanks.Zeigler
I spent hours until I reached here. Thank you. @Gardell Will you marry me?Merideth
S
58

In my case the problem was due to my forgetting to have annotated my Entity classes with @javax.persistence.Entity annotation. Doh!

//The class reported as "not a managed type"
@javax.persistence.Entity
public class MyEntityClass extends my.base.EntityClass {
    ....
}
Scabies answered 29/9, 2016 at 12:5 Comment(3)
In my case I also needed table name in @Entity annotation. I set up a sample project here: github.com/mate0021/two_datasources.gitUniversalist
This was my issue also hibernate 6, spring boot 3.0.2.Byssinosis
this was indeed the issue..Mislead
A
33

I got this error because I stupidly wrote

public interface FooBarRepository extends CrudRepository<FooBarRepository, Long> { ...

A brief explanation: One typically creates a FooBarRepository class to manage FooBar objects (often representing data in a table called something like foo_bar.) When extending the CrudRepository to create the specialized repository class, one needs to specify the type that's being managed -- in this case, FooBar. What I mistakenly typed, though, was FooBarRepository rather than FooBar. FooBarRepository is not the type (the class) I'm trying to manage with the FooBarRepository. Therefore, the compiler issues this error.

I highlighted the mistaken bit of typing in bold. Delete the highlighted word Repository in my example and the code compiles.

Agripinaagrippa answered 25/9, 2019 at 18:32 Comment(5)
15 minutes of my life that I won't be able to recoverStarryeyed
@TayabHussain, I updated the post with some explanation. Hope it helps you out.Agripinaagrippa
You are a genius! :) saved my time.Reconstruction
This helped me, thanks.Anodyne
I have 8+ yrs of experience and still made this mistake today, sometimes we overlook even the simplest mistakes. :DClop
O
25

You can use @EntityScan annotation and provide your entity package for scanning all your jpa entities. You can use this annotation on your base application class where you have used @SpringBootApplication annotation.

e.g. @EntityScan("com.test.springboot.demo.entity")

Onassis answered 6/9, 2017 at 11:6 Comment(0)
E
21

never forget to add @Entity on domain class

Emoryemote answered 28/4, 2018 at 21:6 Comment(1)
What does this answer add to already answered (2 years before, more upvotes) ?Subrogation
K
13

Put this in your Application.java file

@ComponentScan(basePackages={"com.nervy.dialer"})
@EntityScan(basePackages="domain")
Ketone answered 7/12, 2019 at 11:3 Comment(1)
This is a duplicate for the above answer.Frostbite
P
10

Multi-module Maven project

I know @EntityScan was answered before by:

But I felt I needed to emphasize that this problem might occur often when dealing with multi-module Maven project.

In my case, I had a multi-module Maven project, where one module was the model package, and others were microservices. In my case, when I ran a microservice that used a class defined in model package (domain called in my project), I had to add the @EntityScan(basePackages = {"com.example.domain"}) annotation to the @SpringBootApplication class:

@SpringBootApplication
@EnableEurekaClient
@EntityScan(basePackages = {"com.example.domain"}) // add this so the spring boot context knows where to look for entities
public class DoctorServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(DoctorServiceApplication.class, args);
    }

}
Postliminy answered 12/6, 2022 at 9:43 Comment(1)
thank you very much really you are a life saver thanks a lot , and that's exactly what happen to meZaid
W
8

You either missed @Entity on class definition or you have explicit component scan path and this path does not contain your class

Wilhoit answered 13/10, 2017 at 9:30 Comment(1)
This was exactly it. I used a generated project and modified things to my liking and I had org.example as the beginning of my package naming... and had com.example in my entity scan annotation smhWonted
S
6

I have moved my application class to parent package like :

Main class: com.job.application

Entity: com.job.application.entity

This way you don't have to add @EntityScan

Salop answered 28/7, 2020 at 20:16 Comment(2)
this answer worked for me. thanksArmenian
this answer is worked for me too. be careful guys and thanks to answerChrysler
G
5

In my case, I made the mistake of using the repository class as the JpaRepository parameter instead of the entity class. Like this:

@Repository
public interface BuyerInspectionRepository extends JpaRepository<BuyerInspectionRepository,Long> {

}

So i replaced the repository class with the entity class. which is BuyerInspection.

@Repository
public interface BuyerInspectionRepository extends JpaRepository<BuyerInspection,Long> {

}
Greatly answered 7/6, 2022 at 8:45 Comment(0)
M
4

I am using spring boot 2.0 and I fixed this by replacing @ComponentScan with @EntityScan

Mccombs answered 14/3, 2018 at 14:42 Comment(0)
M
4

I had this same problem but only when running spring boot tests cases that required JPA. The end result was that our own jpa test configuration was initializing an EntityManagerFactory and setting the packages to scan. This evidently will override the EntityScan parameters if you are setting it manually.

    final LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter( vendorAdapter );
    factory.setPackagesToScan( Project.class.getPackage().getName());
    factory.setDataSource( dataSource );

Important to note: if you are still stuck you should set a break point in the org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager on the setPackagesToScan() method and take a look at where this is being called and what packages are being passed to it.

Malka answered 10/10, 2019 at 21:1 Comment(0)
R
4

I've reproduced similar issue w/ Not a managed type.

More specifically:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'stockPriceRepository' defined in com.example.stockclient.repository.StockPriceRepository defined in @EnableJpaRepositories declared on StockUiApplication: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.stockclient.StockPrice

As I had multi-module project, I needed to enable auto configuration support for Spring Data JPA required to know the path of JPA repositories, because by default, it will scan only the main application package and its sub packages for detecting JPA repositories.

So in my specific use case I've already used @EnableJpaRepositories to enable the JPA repositories that contains in necessary packages, but without @EntityScan.

With @EntityScan was the same story as with @EnableJpaRepositories, because entity classes weren't placed in the main application package because of multi-module project.

For more details you can refer, for instance, to this article.

Raman answered 11/2, 2022 at 3:33 Comment(0)
Q
3

Don't make an obvious mistake like me and get the order of the templated types incorrect. Make sure you don't have the id first in the templated declaration like:

public interface CapacityBasedProductRepository extends JpaRepository<Long, CapacityBasedProduct> {
}

The JPA class is first and the id column type is second like this:

public interface CapacityBasedProductRepository extends JpaRepository<CapacityBasedProduct, Long> {
}

Otherwise you will get it complaining about java.lang.Long being an unknown entity type. It uses the first item to find an entity to use.

Quadripartite answered 2/12, 2021 at 18:6 Comment(0)
T
3

In my case, I was wrongly importing classes from jakarta.persistence-api.

Importing from javax.persistence.* worked for me:

package foo;
import javax.persistence.Entity;

@Entity
@Table(name = "phone_settings", catalog = "dialer")
public class PhoneSettings implements java.io.Serializable {
   // ...
}
Tuxedo answered 18/4, 2022 at 15:25 Comment(0)
C
2

I had some problem while migrating from Spring boot 1.3.x to 1.5, I got it working after updating entity package at EntityManagerFactory bean

  @Bean(name="entityManagerFactoryDef")
  @Primary
  public LocalContainerEntityManagerFactoryBean defaultEntityManager() {
      Map map = new HashMap();
      map.put("hibernate.default_schema", env.getProperty("spring.datasource.username"));
      map.put("hibernate.hbm2ddl.auto", env.getProperty("spring.jpa.hibernate.ddl-auto"));
      LocalContainerEntityManagerFactoryBean em = createEntityManagerFactoryBuilder(jpaVendorProperties())
              .dataSource(primaryDataSource()).persistenceUnit("default").properties(map).build();
      em.setPackagesToScan("com.simple.entity");
      em.afterPropertiesSet();
      return em;
  }

This bean referred in Application class as below

@SpringBootApplication
@EnableJpaRepositories(entityManagerFactoryRef = "entityManagerFactoryDef")
public class SimpleApp {

}
Celluloid answered 30/3, 2020 at 8:3 Comment(0)
I
2

another way to solve this issue is ...Package of the class containing @SpringBootApplication should be the root and all other packages should be child. For example:

package com.home

@SpringBootApplication
public class TestApplication{
  springapplication.run....
}
 
package com.home.repo

@Repository
public interface StudentRepo implements JpaRepository<Student, int>{
 ..........
}

package com.home.entity

@Entity
@Table(name = "student")
public class Student{
 ..........
}
Interrogatory answered 28/1, 2022 at 4:23 Comment(2)
This answer is correct. As a Java newbie I was porting a project in plain Spring to SpringBoot gradually and started a quick an dirty POC by placing all classes in the same directory and it was throwing the mentioned exception. Make sure at least classes derived from JpaRepository and the ones marked as @Entity are in their own packageBecause
Had the same problem with shared entites between two spring-boot applications. The package has to be organized in a way that the Application is the parent, and the entities must be children.Iso
I
2

In my experience, you should check your annotations. If you use it as a bean, you must use @Component. But as an entity in the repository, you should use @Entity above your class.

Icarus answered 12/10, 2022 at 13:40 Comment(0)
Q
1

Faced similar issue. In my case the repository and the type being managed where not in same package.

Quadrennial answered 20/1, 2021 at 8:58 Comment(2)
They don't need to be in the same package. In fact, they should not be in the same package.Nahshu
Flagged as not-an-answer. This is not helping to solve with a solution, just expressing "same issue" - not an answer.Subrogation
B
0

I have the same probblem, in version spring boot v1.3.x what i did is upgrade spring boot to version 1.5.7.RELEASE. Then the probblem gone.

Blasien answered 1/11, 2017 at 2:53 Comment(3)
I was on a 1.3.x then I switched to 1.5.6 and got the problemAnder
This "same problem" statement is an excellent comment, but not an answer. Please move it to the question's comments.Subrogation
Please provide some link or explanation why migrating to version 1.5.7 does solve the issue.Subrogation
S
0

Below worked for me..

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.apache.catalina.security.SecurityConfig;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

import com.something.configuration.SomethingConfig;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = { SomethingConfig.class, SecurityConfig.class }) //All your configuration classes
@EnableAutoConfiguration
@WebAppConfiguration // for MVC configuration
@EnableJpaRepositories("com.something.persistence.dataaccess")  //JPA repositories
@EntityScan("com.something.domain.entity.*")  //JPA entities
@ComponentScan("com.something.persistence.fixture") //any component classes you have
public class SomethingApplicationTest {

    @Autowired
    private WebApplicationContext ctx;
    private MockMvc mockMvc;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(ctx).build();
    }

    @Test
    public void loginTest() throws Exception {
        this.mockMvc.perform(get("/something/login"))
        .andDo(print()).andExpect(status().isOk());
    }

}
Stove answered 5/4, 2019 at 12:46 Comment(0)
O
0

IN CASE YOU ARE WORKING WITH MULTI MODULE SPRING DATA JPA PROJECT.

If you're working with multiple modules and they have Jpa entities and repositories. This may work for you. I used to get a "Not a managed type" error while deployment on external tomcat(never faced in embedded tomcat).

I had 1 main module and 2 other modules as a dependency. When deployed the main project as a war, I could see a total of 3 Spring applications initializing. When the order of execution is the Main module first and then the child module, no error was there. But sometimes, the child module used to get invoked before the main module. which used to cause "Not a managed type Entity exception"

Tricky thing is, the error won't show up in spring boot embedded tomcat. But when we deploy it in an external tomcat. This exception used to come that too randomly. I had to deploy the same war multiple times to get the order right.

I spent the whole day trying to solve the issue. But turned out the problem was with the way I added my other modules as a dependency in the Main module. If you are adding the spring boot module as a dependency in another project, make sure that the main class is not involved in the jar. When you have another spring boot project as a dependency and when you try to deploy the project as a war. The order of execution of the main application class is not guaranteed. Removing the main class will basically avoid the independent execution of child modules. Hence, there won't be any room for order of execution issue.

Ocarina answered 28/2, 2021 at 16:5 Comment(0)
D
0

For future readers:

Here is the syntax sugar for multiple packages to scan.

Note, my two packages are in different jars as well, but package is the primary driver. Just making note of my 2 jar situation.

    em.setPackagesToScan(new String[] {"com.package.ONE.jpa.entities" , "com.package.TWO.jpa.entities"});

My original ERRANT code below:

    em.setPackagesToScan("com.package.ONE.jpa.entities, com.package.TWO.jpa.entities");

What threw me off was my "xml to java-config swapover". The below shows a simple comma separated value.

The comma-separated list seems to work for di.xml, but not "java config".

Java, and it's ::: "when is it comma-separated, when it is a string-array, when is it a string varargs"....... jig saw puzzle drives me nuts sometimes.

    <!-- the value of "id" attribute below MUST BE "entityManagerFactory"  spring-data voodoo -->
    <bean id="entityManagerFactory"
          class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.package.ONE.jpa.entities, com.package.TWO.jpa.entities"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="${spring.jpa.show-sql}"/>
                <property name="generateDdl" value="${spring.jpa.generate-ddl}"/>
            </bean>
        </property>
        <!-- See https://mcmap.net/q/110156/-how-to-auto-detect-entities-in-jpa-2-0/16088340#16088340 -->
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${spring.jpa.hibernate.ddl-auto}</prop>
                <prop key="hibernate.dialect">${spring.jpa.properties.hibernate.dialect}</prop>
            </props>
        </property>
    </bean>
Donniedonnish answered 29/3, 2021 at 21:59 Comment(2)
The method setPackagesToScan receives a vararg String parameter, so em.setPackagesToScan("com.package.ONE.jpa.entities", "com.package.TWO.jpa.entities"); also works.Elmore
ah, thanks terran. syntax-sugar strikes again.Donniedonnish
S
0

I think it wasn't mentioned by anyone while it's worth noticing that that Not a managed type error might be caused also by package letters case. For example if the package to scan is called myEntities while we provide in package scanning configuration myentities then it might work on one machine while will not work on another so be careful with letter cases.

Scyphus answered 26/8, 2021 at 11:53 Comment(0)
N
0

If you are using a SessionFactory as an EMF:

In my case the problem was that I forgot to include the new entity type, for which I got the error, as an annotated class in the Hibernate configuration.

So, in your SessionFactory bean, don't forget to include this line for your new entity type:

configuration.addAnnotatedClass(MyEntity.class);
Nahshu answered 6/5, 2022 at 11:45 Comment(0)
L
0

I was able to solve this problem by adding below in the appliation.properties file.

spring.jpa.packagesToScan= path of your entity folder like com.java.entity

Livingstone answered 1/8, 2022 at 19:37 Comment(0)
H
0

I was doing the Spring web application tutorial with Kotlin, and I ran into this problem. After some comparison with the official GitHub repository, I realized my mistake: my Entities.kt file was missing its package directive. So I had the following (note the missing package directive):

import com.example.blog.toSlug
import java.time.LocalDateTime
import javax.persistence.*

@Entity
class Article(
    var title: String,
    var headline: String,
    var content: String,
    @ManyToOne var author: User,
    var slug: String = title.toSlug(),
    var addedAt: LocalDateTime = LocalDateTime.now(),
    @Id @GeneratedValue var id: Long? = null)

@Entity
class User(
    var login: String,
    var firstname: String,
    var lastname: String,
    var description: String? = null,
    @Id @GeneratedValue var id: Long? = null)

instead of the correct

package com.example.blog

import java.time.LocalDateTime
import javax.persistence.*

@Entity
class Article(
    var title: String,
    var headline: String,
    var content: String,
    @ManyToOne var author: User,
    var slug: String = title.toSlug(),
    var addedAt: LocalDateTime = LocalDateTime.now(),
    @Id @GeneratedValue var id: Long? = null)

@Entity
class User(
    var login: String,
    var firstname: String,
    var lastname: String,
    var description: String? = null,
    @Id @GeneratedValue var id: Long? = null)

Strangely, I did not get any warnings from IntelliJ.

Herbie answered 10/11, 2022 at 14:4 Comment(0)
A
0

You can check the java version, my problem was solved after changing the version.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.7.1</version>
    <relativePath />
</parent>
Aeschines answered 6/12, 2022 at 12:51 Comment(1)
What has the parent and version of spring-boot-starter-parent to do with "java version" ? Are there compatibility issues? Please explain.Subrogation
P
-1

Adding package to @EntityScan did not help in my case, because there was a factory bean that was specifying packages, so had to add an additional entry there. Then it started working.

Population answered 3/11, 2021 at 2:22 Comment(1)
The answer to use @EntityScan was given multiple times before, e.g. invzbl3. Yours is a duplicate without adding value. Consider removing it and adding the case of "factory bean that was specifying packages" as comment to one of the existing answers.Subrogation

© 2022 - 2024 — McMap. All rights reserved.