Невозможно сохранить объект в таблице с помощью спящего режима (пожалуйста, пройдите вопрос, прежде чем пометить как дубликат) - PullRequest
0 голосов
/ 19 сентября 2018

Я использую API с помощью Spring Boot и пытаюсь сохранить то же самое в базе данных MySql, используя hibernate, но, получая ошибку, я пробовал кое-что, но кое-что, как я застрял с ним.

Трассировка стека

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v2.0.5.RELEASE)

2018-09-20 00:51:26 INFO  com.diwakar.GroupBeema - Starting GroupBeema on LP-PC0MQFY6 with PID 13084 (started by diwakar_b in C:\Diwakar Playground\GroupBeema)
2018-09-20 00:51:26 INFO  com.diwakar.GroupBeema - No active profile set, falling back to default profiles: default
2018-09-20 00:51:26 INFO  o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@12d4bf7e: startup date [Thu Sep 20 00:51:26 IST 2018]; root of context hierarchy
2018-09-20 00:51:27 INFO  o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$c2e2ffe4] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-09-20 00:51:28 INFO  o.s.b.w.e.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
2018-09-20 00:51:28 INFO  o.a.catalina.core.StandardService - Starting service [Tomcat]
2018-09-20 00:51:28 INFO  o.a.catalina.core.StandardEngine - Starting Servlet Engine: Apache Tomcat/8.5.34
2018-09-20 00:51:28 INFO  o.a.c.core.AprLifecycleListener - The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [C:\Program Files\Java\jdk1.8.0_172\bin;C:\WINDOWS\Sun\Java\bin;C:\WINDOWS\system32;C:\WINDOWS;C:/Program Files/Java/jre1.8.0_172/bin/server;C:/Program Files/Java/jre1.8.0_172/bin;C:/Program Files/Java/jre1.8.0_172/lib/amd64;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files\Intel\Intel(R) Management Engine Components\iCLS\;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Windows\CCM;C:\Program Files\PuTTY\;C:\Program Files\Git\cmd;C:\Program Files\Gradle\gradle-4.5.1\bin;C:\WINDOWS\System32\OpenSSH\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Users\diwakar_b\AppData\Local\Microsoft\WindowsApps;;C:\Program Files\Docker Toolbox;C:\Users\diwakar_b\Downloads\eclipse-jee-photon-R-win32-x86_64\eclipse;;.]
2018-09-20 00:51:29 INFO  o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
2018-09-20 00:51:29 INFO  o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 2997 ms
2018-09-20 00:51:29 INFO  o.s.b.w.s.ServletRegistrationBean - Servlet dispatcherServlet mapped to [/]
2018-09-20 00:51:29 INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
2018-09-20 00:51:29 INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-09-20 00:51:29 INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-09-20 00:51:29 INFO  o.s.b.w.s.FilterRegistrationBean - Mapping filter: 'requestContextFilter' to: [/*]
2018-09-20 00:51:29 WARN  o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hibernateUtil': Unsatisfied dependency expressed through field 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionfactory' defined in class path resource [com/diwakar/hibernate/HibernateUtil.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
2018-09-20 00:51:29 INFO  o.a.catalina.core.StandardService - Stopping service [Tomcat]
2018-09-20 00:51:29 INFO  o.s.b.a.l.ConditionEvaluationReportLoggingListener - 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2018-09-20 00:51:29 ERROR o.s.boot.SpringApplication - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'hibernateUtil': Unsatisfied dependency expressed through field 'entityManagerFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionfactory' defined in class path resource [com/diwakar/hibernate/HibernateUtil.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1341)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:572)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:759)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:780)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:412)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:333)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1277)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1265)
    at com.diwakar.GroupBeema.main(GroupBeema.java:10)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionfactory' defined in class path resource [com/diwakar/hibernate/HibernateUtil.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:590)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1247)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1096)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:535)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:495)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
    ... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'hibernateUtil' - consider declaring the factory method as static for independence from its containing instance. Factory method 'getSessionfactory' threw exception; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:582)
    ... 31 common frames omitted
Caused by: java.lang.NullPointerException: null
    at com.diwakar.hibernate.HibernateUtil.getSessionfactory(HibernateUtil.java:19)
    at com.diwakar.hibernate.HibernateUtil$$EnhancerBySpringCGLIB$$462ca353.CGLIB$getSessionfactory$0(<generated>)
    at com.diwakar.hibernate.HibernateUtil$$EnhancerBySpringCGLIB$$462ca353$$FastClassBySpringCGLIB$$adc355b2.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:365)
    at com.diwakar.hibernate.HibernateUtil$$EnhancerBySpringCGLIB$$462ca353.getSessionfactory(<generated>)
    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:498)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 32 common frames omitted

Класс GroupBeema

package com.diwakar;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;



    @SpringBootApplication
    public class GroupBeema{

        public static void main(String[] args) {
            SpringApplication.run(GroupBeema.class, args);
        }
    }

InsurerController

package com.diwakar.insurer;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.diwakar.hibernate.InsurerDao;

@RestController
public class InsurerController {

    @Autowired
    public InsurerService insurerService;

    @Autowired
    private InsurerDao insurerDao;

    @RequestMapping("/insure")
    public List<Insurer> getInsurersInfo() {
        List<Insurer> list = insurerService.getAllInsurer();
        //insurerService.createTable(list);
        insurerDao.createInsurer(list);
        return list;
    }

}

СтраховщикСервис

package com.diwakar.insurer;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

@Service
public class InsurerService {

    public List<Insurer> getAllInsurer( ) {

        List<Insurer> list = new ArrayList<Insurer>();

        try {
            Client client = Client.create();
            WebResource webResource = client.resource("https://termlife.policybazaar.com/api/v1/quotes");

            String input = "//some json data"

            ClientResponse response = webResource.type("application/json").post(ClientResponse.class, input);

            if (response.getStatus() != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + response.getStatus());
            }

            String output = response.getEntity(String.class);
            JSONArray jsonArray = new JSONArray(output);
            for(int n = 0; n < jsonArray.length(); n++) {
                JSONObject obj = jsonArray.getJSONObject(n);
                Insurer ins = new Insurer();
                ins.setBasicPremium(obj.getInt("BasicPremium"));
                ins.setE2EName(obj.getString("E2EName"));
                ins.setE2ESupplier(obj.getString("E2ESupplier"));
                list.add(ins);
            }

        } catch (Exception e) {
            e.printStackTrace();
          }
        return list;
    }

}

HibernateUtil

package com.diwakar.hibernate;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HibernateUtil {

    @Autowired
    private EntityManagerFactory entityManagerFactory;

    @Bean
    public SessionFactory getSessionfactory() {
        if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
            //throw new NullPointerException("factory is not hibernate factory.!!");
            System.out.println("Exception in getSessionfactory method..");
        }
        return entityManagerFactory.unwrap(SessionFactory.class);
    }
}

СтраховщикDAO

package com.diwakar.hibernate;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.diwakar.insurer.Insurer;

@Repository
public class InsurerDao {

    @Autowired
    private SessionFactory sessionFactory;

    public void createInsurer(List<Insurer> insurer) {
        Session session = null;
        //SessionFactory sessionFactory = null;
        try {
            //sessionFactory = new Configuration().buildSessionFactory();
            session = sessionFactory.openSession();
            session.beginTransaction();
            Integer i = (Integer) session.save(insurer);
            System.out.println("Insurer table is created with " + i + " records..!!");
            session.getTransaction().commit();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
}

Свойства применения

//assume everything is correct

Ответы [ 2 ]

0 голосов
/ 21 сентября 2018

Проблема с вашим кодом в том, что SessionFactory является подынтерфейсом для EntityManagerFactory.Даже если вы измените это значение на EntityManager, оно не будет работать, так как EntityManager зависит от EntityManagerFactory и, следовательно, метод для этого вызывается первым в жизненном цикле при запуске.Не могли бы вы объяснить, зачем вам нужен SessionFactory?Если вы хотите получить EntityManager, вы можете просто ввести его, используя @PersistenceContext в своих службах.

0 голосов
/ 20 сентября 2018

Вы не можете автоматически подключаться в классе конфигурации, передавая ваши зависимости как параметры

Таким образом, ваш HibernateUtil должен выглядеть следующим образом:

@Configuration
public class HibernateUtil {

    @Bean
    public SessionFactory getSessionfactory(EntityManagerFactory entityManagerFactory) {
        if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
            //throw new NullPointerException("factory is not hibernate factory.!!");
            System.out.println("Exception in getSessionfactory method..");
        }
        return entityManagerFactory.unwrap(SessionFactory.class);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...