不是托管类型:类实体。 & 弹簧数据

Posted

技术标签:

【中文标题】不是托管类型:类实体。 & 弹簧数据【英文标题】:Not an managed type: class entity. & Spring Data 【发布时间】:2015-11-27 22:25:27 【问题描述】:

我正在使用spring data,我使用@Bean@EntityMain.java 创建配置类,但运行项目时出现异常:

Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class entity.Todo

我的Main.java

    public class Main 

    @Autowired
    private static TodoRepository todoRepository;

    public static void main(String[] args) 
        Todo todo = new Todo();
        todo.setId(1l);
        todo.setTitle("title");
        System.out.println(todoRepository); //null
        todoRepository.save(todo);          //Exception in thread "main" java.lang.NullPointerException
    

PersistenceContext.java

@Configuration
@EnableJpaRepositories(basePackages = "repository",
        entityManagerFactoryRef = "entityManagerFactory",
        transactionManagerRef = "transactionManager")
@EnableTransactionManagement
@PropertySource("classpath:app.properties")
public class PersistenceContext 

    public PersistenceContext() 
    

    /**
     * The method that configures the datasource bean
     * */

    @Resource
    private Environment env;

    @Bean(destroyMethod = "close")
    DataSource dataSource() 
        HikariConfig dataSourceConfig = new HikariConfig();
        dataSourceConfig.setJdbcUrl(env.getRequiredProperty("db.url"));
        dataSourceConfig.setDriverClassName(env.getRequiredProperty("db.driver"));
        dataSourceConfig.setUsername(env.getRequiredProperty("db.username"));
        dataSourceConfig.setPassword(env.getRequiredProperty("db.password"));
        return new HikariDataSource(dataSourceConfig);
    

    /**
     * The method that configures the entity manager factory
     * */
    @Bean
    LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource, Environment env) 
        LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
        entityManagerFactoryBean.setDataSource(dataSource);
        entityManagerFactoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
        entityManagerFactoryBean.setPackagesToScan("net.petrikainulainen.springdata.jpa.todo");

        Properties jpaProperties = new Properties();

        jpaProperties.put("hibernate.dialect", env.getRequiredProperty("hibernate.dialect"));
        jpaProperties.put("hibernate.hbm2ddl.auto", env.getRequiredProperty("hibernate.hbm2ddl.auto"));
        jpaProperties.put("hibernate.show_sql", env.getRequiredProperty("hibernate.show_sql"));
        jpaProperties.put("hibernate.format_sql", env.getRequiredProperty("hibernate.format_sql"));

        entityManagerFactoryBean.setJpaProperties(jpaProperties);

        return entityManagerFactoryBean;
    

    /**
     * The method that configures the transaction manager
     * */
    @Bean
    JpaTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) 
        JpaTransactionManager transactionManager = new JpaTransactionManager();
        transactionManager.setEntityManagerFactory(entityManagerFactory);
        return transactionManager;
    

Todo.java

@Entity
@Table(name = "todos")
public class Todo 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "title", nullable = false, length = 100)
    private String title;

    public Todo() 
    
    //getter setter tostring

所有堆栈跟踪:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
сен 02, 2015 2:54:49 PM org.hibernate.jpa.internal.util.LogHelper logPersistenceUnitInformation
INFO: HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
sep 02, 2015 2:54:49 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core 5.0.0.Final
sep 02, 2015 2:54:49 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
sep 02, 2015 2:54:49 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
sep 02, 2015 2:54:49 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations 5.0.0.Final
sep 02, 2015 2:54:49 PM org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.mysqlDialect
sep 02, 2015 2:54:50 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000227: Running hbm2ddl schema export
sep 02, 2015 2:54:50 PM org.hibernate.tool.hbm2ddl.SchemaExport execute
INFO: HHH000230: Schema export complete
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'todoRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not an managed type: class entity.Todo
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1554)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:539)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:302)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:229)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:298)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:687)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:762)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
    at org.springframework.context.annotation.AnnotationConfigApplicationContext.<init>(AnnotationConfigApplicationContext.java:84)
    at Main.main(Main.java:21)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Caused by: java.lang.IllegalArgumentException: Not an managed type: class entity.Todo
    at org.hibernate.jpa.internal.metamodel.MetamodelImpl.managedType(MetamodelImpl.java:210)
    at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:68)
    at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:67)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:146)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:90)
    at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:70)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:171)
    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:1613)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1550)
    ... 16 more

Process finished with exit code 1

【问题讨论】:

【参考方案1】:

您的 Todo 类名称(如错误消息所示)是 entity.Todo。所以它在包里entity

但是你的实体管理器工厂是这样配置的:

entityManagerFactoryBean.setPackagesToScan("net.petrikainulainen.springdata.jpa.todo");

因此您的entity 包不会被扫描,因此JPA 不知道Todo 实体。

【讨论】:

谢谢,这解决了我的问题。也许你知道为什么我在使用 @Autowired 时会出错 (delete ApplicationContext) 我在 todoRepository.save(todo); 行中得到异常 Exception in thread "main" java.lang.NullPointerException 你没有发布 TodoRepository 的任何代码行。如果此答案解决了您的问题,您应该通过勾选问题旁边的灰色标记来接受它。如果您遇到其他问题,请使用相关代码提出另一个问题。 好吧,我创建新问题!【参考方案2】:

对于 Spring boot,您必须在 application.properties 中定义 entitymanager.packagesToScan 属性,如下所示;

entitymanager.packagesToScan = com.app.domain

【讨论】:

【参考方案3】:

在处理休眠时,请始终检查repositoriesentityManagerFactory 下的包扫描以及&lt;context:component-scan base-package="com.company"/&gt;

<jpa:repositories base-package="com.company" />
<bean class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" id="mysql_dataSource">
    <property name="driverClassName" value="$database.driverClassName" />
    <property name="url" value="$database.url" />
    <property name="username" value="$database.username" />
    <property name="password" value="$database.password" />
    <property name="testOnBorrow" value="$database.connectionPool.testOnBorrow" />
    <property name="testOnReturn" value="$database.connectionPool.testOnReturn" />
    <property name="testWhileIdle" value="$database.connectionPool.testWhileIdle" />
    <property name="timeBetweenEvictionRunsMillis" value="$database.connectionPool.timeBetweenEvictionRunsMillis" />
    <property name="numTestsPerEvictionRun" value="$database.connectionPool.numTestsPerEvictionRun" />
    <property name="minEvictableIdleTimeMillis" value="$database.connectionPool.minEvictableIdleTimeMillis" />
    <property name="maxWait" value="$database.connectionPool.maxWait"/>
    <property name="maxActive" value="$database.connectionPool.maxActive"/>
    <property name="maxIdle" value="$database.connectionPool.maxIdle"/>
    <property name="minIdle" value="$database.connectionPool.minIdle"/>
    <property name="initialSize" value="$database.connectionPool.initialSize"/>
    <property name="validationQuery" value="$database.connectionPool.validationQuery" />
</bean>

<bean class="org.springframework.orm.jpa.JpaTransactionManager"
    id="transactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>

<bean
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    id="entityManagerFactory">
    <property name="persistenceUnitName" value="persistenceUnit" />
    <property name="packagesToScan">
        <list>
            <value>com.company</value>
        </list>
    </property>
    <property name="dataSource" ref="mysql_dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
    </property>
    <property name="jpaProperties">
        <props>
            <prop key="hibernate.archive.autodetection">class,hbm</prop>
            <prop key="hibernate.hbm2ddl.auto">none</prop>
            <prop key="hibernate.show_sql">true</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
            <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.DefaultNamingStrategy</prop>
            <prop key="hibernate.connection.charSet">UTF-8</prop>
        </props>
    </property>
</bean>

【讨论】:

【参考方案4】:

如果您使用的是 Eclipse IDE,请单击运行配置并确保选中了 Resolve Workspace artifact 复选框。它对我有用enter image description here

【讨论】:

以上是关于不是托管类型:类实体。 & 弹簧数据的主要内容,如果未能解决你的问题,请参考以下文章

异常消息是在数据上下文类型上有一个*** IQueryable 属性,其元素类型不是实体类型

spring data jpa:不是托管类型:xxx类

自动装配失败:不是托管类型

JPA 混淆(托管与非托管实体)

用于存储简单实体的 AWS 托管数据存储

弹簧数据 JPA。子实体的分页