简体   繁体   中英

Spring and Hibernate 5. SessionFactory always null

I´ve spent several hours trying to make this work, but I always get the same result, SessionFactory is always null. I´m using Spring Boot and Hibernate 5.

I´ve tried a lot of possible solutions from here and other webpages, and I can´t solve it. It seems @Autowire annotation is not working. Here´s the complete code. It´s so empty because I´m in the begining of the project.

EDIT: I´ve edited all to adjust like other users said me, but I´m getting another error.

And now the error says this:

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

main

@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 --> Here´s where SessionFactory has a null value

    @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);
    }
}

This is the class that has the code for the necessary configuration

@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);
    }
}

if you don't use DI for inject your DAO (userDAO). All annotations in userDao class won't work.

Please update your code like this:

@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);
        }  
}

Remember always use java naming conventions

You are overthinking things and making things to complex. Instead of the plain Hibernate API just use JPA. You don't need the SessionConfig ditch it.

Your CibervoluntariosAppApplication should only have the main method, the annotated methods in there don't really make sense.

@SpringBootApplication
public class CibervoluntariosAppApplication {

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

Now your UserDao should use the EntityManager (already provided by Spring Boot) instead of the SessionFactory .

@Repository
public class userDAO {

    @PersistenceContext
    private EntityManager em;

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

And instead of manually doing transaction management add @Transactional to your @Service annotated class.

@Service
@Transactional
public class LoginService {

    @Autowired
    private userDAO userManagement;

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

All this reduces the code you have to write and it reduces complexity due to removing the unnecessary beans from your configuration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM