2015-09-02 21 views
13

pracuję z spring data, tworzę klasę config z @Bean, @Entity i Main.java ale kiedy uruchomić projekt i uzyskać wyjątek:Nie jest zarządzanym typem: encja klasy. & Wiosna danych

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

Moja 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 
} 

Wszystko StackTrace:

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 

Odpowiedz

22

Twój Todo nazwa klasy, jak wynika z komunikatu o błędzie, to entity.Todo. Więc jest w pakiecie entity.

Ale menedżer jednostka fabrycznie jest skonfigurowany w ten sposób:

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

Więc pakiet entity nie jest skanowany, a jednostka Todo jest więc nieznane WZP.

+1

Dziękuję, to rozwiązać mój problem. Może wiesz, dlaczego mam błąd, gdy używam '@ Autowired' * (usuń' ApplicationContext') * otrzymuję wyjątek 'Exception in thread" main "java.lang.NullPointerException' w linii' todoRepository.save (todo); ' –

+0

Nie wpisałeś żadnej linii kodu TodoRepository. Jeśli ta odpowiedź rozwiązała Twój problem, powinieneś ją zaakceptować, zaznaczając szary znak obok pytania. Jeśli utknąłeś z innym problemem, zadaj * kolejne * pytanie z odpowiednim kodem. –

+0

Okey, tworzę nowe pytanie! –

6

W przypadku rozruchu typu Spring należy zdefiniować właściwości Diplodymanager.packagesToScan w application.properties, jak poniżej;

entitymanager.packagesToScan = com.app.domain

0

Natomiast do czynienia z hibernacji zawsze sprawdzić skanowanie pakietów pod repositories i entityManagerFactory wraz z <context:component-scan base-package="com.company"/>

<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>