2015-05-05 2 views
0

Заголовок вопроса может быть таким же, но я попытался решить эту ошибку, посмотрев предыдущие ответы, но ничего не происходит. Я получаю следующую ошибку при вставке данных в базу данных. Таблицы создаются, но при вставке данных в базу данных возникает ошибка.Не удалось автополе при вставке данных в базу данных

SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'InitDbService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.app.flight.repo.RoleRepository com.app.flight.service.InitDbService.roleRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'roleRepository': Cannot create inner bean '(inner bean)#397030fe' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#397030fe': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' is defined 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) 

Это мой класс Role.java объект

@Entity 
public class Role { 
    @Id 
    @GeneratedValue 
    private Integer id; 
    private String name; 

    (getters and setters) 

Это RoleRepository.java интерфейс

package com.app.flight.repo; 

import org.springframework.data.jpa.repository.JpaRepository; 
import com.app.flight.entity.Role; 

public interface RoleRepository extends JpaRepository<Role, Integer> { 

} 

Это класс обслуживания и InitDbService.java

package com.app.flight.service; 

import javax.annotation.PostConstruct; 
import javax.transaction.Transactional; 

import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Service; 
import com.app.flight.entity.Role; 
import com.app.flight.repo.RoleRepository; 

@Transactional 
@Service 
public class InitDbService { 

    @Autowired 
    private RoleRepository roleRepository; 

    @PostConstruct 
    public void init(){ 

     Role roleUser = new Role(); 
     roleUser.setName("ROLE_USER"); 
     roleRepository.save(roleUser); 

     Role roleAdmin= new Role(); 
     roleAdmin.setName("ROLE_ADMIN"); 
     roleRepository.save(roleAdmin); 

    } 
} 

Это applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:jdbc="http://www.springframework.org/schema/jdbc" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:jpa="http://www.springframework.org/schema/data/jpa" 
    xmlns:repository="http://www.springframework.org/schema/data/repository" 
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd 
     http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.8.xsd 
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd 
     http://www.springframework.org/schema/data/repository http://www.springframework.org/schema/data/repository/spring-repository-1.7.xsd"> 

<context:component-scan base-package="com.app.flight"> 
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> 
</context:component-scan> 

<jdbc:embedded-database type="HSQL" id="dataSource"/> 

<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="emf"> 
    <property name="packagesToScan" value="com.app.flight.entity"/> 
    <property name="dataSource" ref="dataSource"/> 
    <property name="jpaProperties"> 
     <props> 
      <prop key="hibernate.show_sql">true</prop> 
      <prop key="hibernate.hbm2ddl.auto">create</prop> 
     </props> 
    </property> 
    <property name="persistenceProvider"> 
     <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/> 
    </property> 
</bean> 

<tx:annotation-driven transaction-manager="transactionManager"/> 

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

<jpa:repositories base-package="com.app.flight.repo"/> 

</beans> 

ответ

4

Он ожидает, что EntityManagerFactory имеет конкретное имя в этом случае «EntityManagerFactory». Вы определили пользовательское имя "emf". Я предполагаю, что проблема решена, если вы адаптируете запись в XML-файле.

+0

** It works, Great **. Огромное спасибо. Могу ли я узнать, почему я не могу использовать его как 'emf'? – RYJ

+0

Отметьте ответ как правильный, чтобы он был виден как разрешенный. Spring использует соглашение по конфигурации для многих вещей, чтобы упростить его использование. Spring boot может самостоятельно настроить функцию entitymanager. Вы делаете это только вручную, если вам нужно что-то обычай. –

+0

Если вы воспользовались настройкой bean-конфигурации, вы можете проверить следующее:> https://github.com/mh-dev/blog_springBoot-jpa-multiProject/blob/master/common/src/main/java/mh /dev/blog/multi/common/config/DatabaseConfiguration.java –