Je travaille avec spring data
, je crée une classe de configuration avec @Bean
, @Entity
et Main.Java
mais lors de l'exécution du projet, je reçois une exception
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
Mon 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
}
Tout 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
Votre nom de classe Todo, comme indiqué par le message d'erreur, est entity.Todo
. Donc, c'est dans le paquet entity
.
Mais votre fabrique de gestionnaires d’entités est configurée de la manière suivante:
entityManagerFactoryBean.setPackagesToScan("net.petrikainulainen.springdata.jpa.todo");
Donc, votre paquet entity
n'est pas analysé, et l'entité Todo
est donc inconnue de JPA.
Pour le démarrage du printemps, vous devez définir les propriétés entitymanager.packagesToScan dans application.properties comme ci-dessous;
entitymanager.packagesToScan = com.app.domain
Lorsque vous travaillez en veille prolongée, vérifiez toujours l’analyse des paquets sous repositories
et entityManagerFactory
avec <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>