Spring和Hibernate 5. SessionFactory总是为null

时间:2017-12-27 01:12:52

标签: java hibernate spring-boot sessionfactory

我花了几个小时试图完成这项工作,但我总是得到相同的结果,SessionFactory总是为null。我正在使用Spring Boot和Hibernate 5.

我已经从这里和其他网页尝试了很多可能的解决方案,我无法解决它。似乎@Autowire注释不起作用。这是完整的代码。它太空了,因为我正处于项目的开始阶段。

编辑:我编辑了所有调整,就像其他用户说的那样,但我收到了另一个错误。

现在错误说明了这一点:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sessionConfig': 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/cibervoluntarios/app/util/SessionConfig.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 'sessionConfig' - 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) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:138) ~[spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:751) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:387) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1245) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1233) [spring-boot-2.0.0.BUILD-SNAPSHOT.jar:2.0.0.BUILD-SNAPSHOT]
    at com.cibervoluntarios.app.CibervoluntariosPruebas2Application.main(CibervoluntariosPruebas2Application.java:12) [classes/:na]
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSessionFactory' defined in class path resource [com/cibervoluntarios/app/util/SessionConfig.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 'sessionConfig' - 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:587) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1250) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1099) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:545) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:251) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1135) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    ... 19 common frames omitted
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.hibernate.SessionFactory]: Circular reference involving containing bean 'sessionConfig' - 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) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    ... 31 common frames omitted
Caused by: java.lang.NullPointerException: null
    at com.cibervoluntarios.app.util.SessionConfig.getSessionFactory(SessionConfig.java:16) ~[classes/:na]
    at com.cibervoluntarios.app.util.SessionConfig$$EnhancerBySpringCGLIB$$870befb7.CGLIB$getSessionFactory$0(<generated>) ~[classes/:na]
    at com.cibervoluntarios.app.util.SessionConfig$$EnhancerBySpringCGLIB$$870befb7$$FastClassBySpringCGLIB$$4a4fa31.invoke(<generated>) ~[classes/:na]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228) ~[spring-core-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361) ~[spring-context-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    at com.cibervoluntarios.app.util.SessionConfig$$EnhancerBySpringCGLIB$$870befb7.getSessionFactory(<generated>) ~[classes/:na]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_152]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_152]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_152]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_152]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.0.2.RELEASE.jar:5.0.2.RELEASE]
    ... 32 common frames omitted

@SpringBootApplication
public class CibervoluntariosAppApplication {

    private userDAO prueba;

        @RequestMapping("/")
        @ResponseBody
        String home() {
            return "Hello World. How are you?";
        }

        @RequestMapping("/user")
        @ResponseBody
        String isertuser() {
            prueba = new userDAO();
            users user = new users();
            user.setPassword("qwerty");
            BigInteger cosa = new BigInteger("12345678");
            user.setSocial_id(cosa);
            user.setSocial_network("Facebook");
            user.setUsername("Pepe");
            prueba.insertUser(user);
            return "Test";
        }

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

users.java

@Entity
@Table(name = "users")
public class users {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private BigInteger id;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

    @Column(name = "social_id")
    private BigInteger social_id;

    @Column(name = "social_network")
    private String social_network;

    public BigInteger getId() {
        return id;
    }

    public void setId(BigInteger id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public BigInteger getSocial_id() {
        return social_id;
    }

    public void setSocial_id(BigInteger social_id) {
        this.social_id = social_id;
    }

    public String getSocial_network() {
        return social_network;
    }

    public void setSocial_network(String social_network) {
        this.social_network = social_network;
    }

}

usersDAO - &gt;这是SessionFactory具有空值的地方

    @Repository
public class userDAO {

    private SessionFactory sessionFactory;

    public void insertUser(users user) {
        Session session = null;
        try {           
            session = sessionFactory.getCurrentSession();
            session.beginTransaction();
            session.save(user);
            session.getTransaction().commit();
        }catch (Exception e) {
            session.getTransaction().rollback();
        }
    }

    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }


}

LoginService.java

@Service
public class LoginService {

    @Autowired
    private userDAO userManagement;

    public void insertUser(users userToAdd) {
        this.userManagement.insertUser(userToAdd);
    }
}

SignInController

@RestController
@RequestMapping("/")
public class SignInController {

    @Autowired
    private LoginService loginService;

    @RequestMapping("/hello")
    @ResponseBody
    public String home() {
        return "Hello World. How are you?";
    }

    @RequestMapping("/add")
    public void insertUser() {
        users user = new users();
        user.setPassword("qwerty");
        BigInteger cosa = new BigInteger("12345678");
        user.setSocial_id(cosa);
        user.setSocial_network("Facebook");
        user.setUsername("Pepe");
        this.loginService.insertUser(user);
    }
}

这是具有必要配置代码的类

@Configuration
public class SessionConfig {

    @Bean
    public SessionFactory sessionFactory(@Autowired EntityManagerFactory factory) {
            if (factory.unwrap(SessionFactory.class) == null) {
                throw new NullPointerException("factory is not a hibernate factory");
            }
            return factory.unwrap(SessionFactory.class);
    }
}

2 个答案:

答案 0 :(得分:0)

如果您不使用DI注入您的DAO(userDAO)。 userDao类中的所有注释都不起作用。

请更新您的代码:

@SpringBootApplication
@Controller
public class CibervoluntariosAppApplication {

    @Autowired
    private userDAO prueba;

        @RequestMapping("/")
        @ResponseBody
        String home() {
            return "Hello World. How are you?";
        }

        @RequestMapping("/user")
        @ResponseBody
        String isertuser() {
            users user = new users();
            user.setPassword("qwerty");
            BigInteger cosa = new BigInteger("12345678");
            user.setSocial_id(cosa);
            user.setSocial_network("Facebook");
            user.setUsername("Pepe");
            prueba.insertUser(user);
            return "Test";
        }

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

请记住始终使用java naming conventions

答案 1 :(得分:0)

你正在过度思考事物并使事情变得复杂。而不是简单的Hibernate API只使用JPA。你不需要SessionConfig沟渠。

您的CibervoluntariosAppApplication应该只使用main方法,其中带注释的方法确实没有意义。

@SpringBootApplication
public class CibervoluntariosAppApplication {

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

现在您的UserDao应该使用EntityManager(已经由Spring Boot提供)而不是SessionFactory

@Repository
public class userDAO {

    @PersistenceContext
    private EntityManager em;

    public void insertUser(users user) {
        em.persist(user);
    }
}

而不是手动执行事务管理,而是将@Transactional添加到@Service带注释的类中。

@Service
@Transactional
public class LoginService {

    @Autowired
    private userDAO userManagement;

    public void insertUser(users userToAdd) {
        this.userManagement.insertUser(userToAdd);
    }
}

所有这些都减少了您必须编写的代码,并且由于从配置中删除了不必要的bean,因此降低了复杂性。