2015-10-14 2 views
0

Мой Java на основе конфигурации являетсяНе удалось создать экземпляр компонента. вложенное исключение java.lang.NullPointerException

@Configuration 
@ComponentScan(basePackages = { "com.doly.jproject" }) 
@EnableTransactionManagement 
@EnableJpaRepositories (basePackages = "com.doly.jproject.repository") 
public class RootConfigurer extends WebMvcConfigurerAdapter { 

    private Properties jpaProperties; 

    @Bean 
    public DriverManagerDataSource dataSource() { 
     DriverManagerDataSource dataSource = new DriverManagerDataSource(); 
     dataSource.setDriverClassName("com.mysql.jdbc.Driver"); 
     dataSource.setUrl("jdbc:mysql://localhost/dbga"); 
     dataSource.setUsername("root"); 
     dataSource.setPassword(""); 
     return dataSource; 
    } 

    @Bean 
    public EntityManagerFactory entityManagerFactory() throws SQLException { 

     LocalContainerEntityManagerFactoryBean entityManagerFactory = 
       new LocalContainerEntityManagerFactoryBean(); 
     entityManagerFactory.setPackagesToScan("com.doly.jproject.entity"); 
     entityManagerFactory.setDataSource(dataSource()); 

     jpaProperties = new Properties();  
     jpaProperties.put("hibernate.show_sql", true); 
     jpaProperties.put("hibernate.hbm2ddl.auto", "create"); 

     entityManagerFactory.setJpaProperties(jpaProperties); 
     entityManagerFactory.setPersistenceProvider(new HibernatePersistenceProvider()); 

     return entityManagerFactory.getObject(); 
    } 


    @Bean 
    @Qualifier(value = "entityManager") 
    public EntityManager entityManager(EntityManagerFactory entityManagerFactory) { 
     return entityManagerFactory.createEntityManager(); 
    } 

    @Bean 
    public JpaTransactionManager transactionManager() { 
     JpaTransactionManager transactionManager = new JpaTransactionManager(); 
     transactionManager.setDataSource(dataSource()); 
     return transactionManager; 
    } 
} 

, но когда я хочу, чтобы инициализировать объект org.hibernate.Session из javax.persistence.EntityManager в моем классе @Service, как

@Autowired 
@Qualifier(value = "entityManager") 
private EntityManager entityManager;  
private Session session = entityManager.unwrap(org.hibernate.Session.class); 

Я получаю ошибку + StackTrace в

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 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.doly.jproject.service.VidService com.doly.jproject.controllers.HomeController.vidService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidService' defined in file [F:\Spring Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\jobsnetwork\WEB-INF\classes\com\doly\jproject\service\VidService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.doly.jproject.service.VidService]: Constructor threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) 
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) 
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) 
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) 
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) 
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5014) 
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528) 
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) 
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) 
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 
    at java.lang.Thread.run(Thread.java:745) 
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.doly.jproject.service.VidService com.doly.jproject.controllers.HomeController.vidService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidService' defined in file [F:\Spring Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\jobsnetwork\WEB-INF\classes\com\doly\jproject\service\VidService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.doly.jproject.service.VidService]: Constructor threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) 
    ... 22 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.doly.jproject.service.VidService com.doly.jproject.controllers.HomeController.vidService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidService' defined in file [F:\Spring Workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\jobsnetwork\WEB-INF\classes\com\doly\jproject\service\VidService.class]: Instantiation of bean failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.doly.jproject.service.VidService]: Constructor threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1101) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) 
    ... 24 more 
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.doly.jproject.service.JobService]: Constructor threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:163) 
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:89) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1094) 
    ... 35 more 
Caused by: java.lang.NullPointerException 
    at com.doly.jproject.service.VidService.<init>(VidService.java:42) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) 
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) 
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) 
    at java.lang.reflect.Constructor.newInstance(Constructor.java:422) 
    at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147) 
    ... 37 more 

и com.doly.jproject.service.VidService.<init>(VidService.java:42) является

и

public void updateJobCategory(Video video) { 
     Video video = (Video)session.get(Video.class, id);// Here it causes com.doly.jproject.service.VidService.<init>(VidService.java:42) 
video.getCustomers().clear();//removes all the existing customers 
Customer customer1 = new Customer(); 
customer1.getVideos().add(video)//adding video to the customer 
video.getCustomers().add(customer1); 
session.update(video) 


    } 

UPDATE Когда я изменяю

@Autowired 
    @Qualifier(value = "entityManager") 
    private EntityManager entityManager;  
    private Session session; 

и в методе обновления я пишу

public void updateJobCategory(Video video) { 
    session= entityManager.unwrap(org.hibernate.Session.class); 
    Video video = (Video)session.get(Video.class, id); 
    video.getCustomers().clear();//removes all the existing customers 
    Customer customer1 = new Customer(); 
    customer1.getVideos().add(video)//adding video to the customer 
    video.getCustomers().add(customer1); 
    session.update(video) 


     } 

Я получаю

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 'homeController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.doly.jproject.service.VidService com.doly.jproject.controllers.HomeController.vidService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.doly.jproject.repository.VidRepository com.doly.jproject.VidService.vidRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidRepository': Cannot create inner bean '(inner bean)#681afbff' 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)#681afbff': Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManager]: Factory method 'createSharedEntityManager' threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:755) 
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:757) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480) 
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403) 
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306) 
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106) 
    at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5014) 
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528) 
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150) 
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575) 
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565) 
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) 
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) 
    at java.lang.Thread.run(Thread.java:745) 
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.doly.jproject.service.VidService com.doly.jproject.controllers.HomeController.vidService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.doly.jproject.repository.VidRepository com.doly.jproject.service.VidService.vidRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidRepository': Cannot create inner bean '(inner bean)#681afbff' 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)#681afbff': Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManager]: Factory method 'createSharedEntityManager' threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) 
    ... 22 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.rhcloud.jobsnetwork.repository.JobRepository com.doly.jproject.service.VidService.vidRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidRepository': Cannot create inner bean '(inner bean)#681afbff' 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)#681afbff': Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManager]: Factory method 'createSharedEntityManager' threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) 
    ... 24 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.doly.jproject.repository.VidRepository com.doly.jproject.service.VidService.vidRepository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidRepository': Cannot create inner bean '(inner bean)#681afbff' 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)#681afbff': Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManager]: Factory method 'createSharedEntityManager' threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331) 
    ... 35 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'vidRepository': Cannot create inner bean '(inner bean)#681afbff' 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)#681afbff': Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManager]: Factory method 'createSharedEntityManager' threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:313) 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:129) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1477) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1222) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:1120) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1044) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533) 
    ... 37 more 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#681afbff': Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManager]: Factory method 'createSharedEntityManager' threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:599) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476) 
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:299) 
    ... 50 more 
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.persistence.EntityManager]: Factory method 'createSharedEntityManager' threw exception; nested exception is java.lang.NullPointerException 
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:189) 
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:588) 
    ... 55 more 
Caused by: java.lang.NullPointerException 
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.initProxyClassLoader(SharedEntityManagerCreator.java:198) 
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.<init>(SharedEntityManagerCreator.java:190) 
    at org.springframework.orm.jpa.SharedEntityManagerCreator.createSharedEntityManager(SharedEntityManagerCreator.java:162) 
    at org.springframework.orm.jpa.SharedEntityManagerCreator.createSharedEntityManager(SharedEntityManagerCreator.java:119) 
    at org.springframework.orm.jpa.SharedEntityManagerCreator.createSharedEntityManager(SharedEntityManagerCreator.java:91) 
    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 org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) 
    ... 56 more 

Как я могу получить org.hibernate.Session от javax.persistence.EntityManager в моем классе @Service? пожалуйста помоги!

+0

У компонента, создающего проблему, возникает проблема 'com.doly.jproject.service.VidService', из-за NPE в его конструкторе. Очень важно прочитать всю трассировку стека, чтобы определить причину ошибки. Где код для 'VidService'? –

+0

Значит, я размещаю полный стек? – Faqeer

+1

ВСЕГДА публикует всю полную трассировку стека и идентифицирует строку в коде, в котором возникает исключение. –

ответ

3

Это кажется проблематичным для меня:

@Autowired 
@Qualifier(value = "entityManager") 
private EntityManager entityManager;  
private Session session = entityManager.unwrap(org.hibernate.Session.class); 

происходит после автоматического связывания вашего объекта строится. Это означает, что когда ваши службы будут созданы, он попытается позвонить entityManager.unwrap до того, как будет установлен entityManager.

Кроме того, обычно не рекомендуется сохранять сеанс таким образом. Вы должны создать новый EntityManager/Session для каждой операции/транзакции, которую вы выполняете. То, как вы настроили вещи, будет только один компонент EntityManager для вашего приложения, что приведет к проблемам. То, что вы, вероятно, хотите:

@Autowired 
private EntityManagerFactory entityManagerFactory; 

, а затем

public void doStuff() { 
    EntityManager entityManager = entityManagerFactory.createEntityManager(); 
} 

Поскольку вы уже используете Spring вы можете посмотреть в аннотации @Transactional также.

+0

Извините, это дает мне исключение, как указано в __UPDATE__ – Faqeer

Смежные вопросы

 Смежные вопросы