Home > Blockchain >  Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method &
Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: Factory method &

Time:09-17

I am having problem implementing hibernate in my project. I am getting error saying

java.lang.NullPointerException in sessionFactory

Below is the error log and configuration file. Please do not suggest me xml type of configuration.

Error log is:

{"logType":"DEBUG",
 "logLevel":"ERROR",
 "logTimestamp":"2021-09-11T20:28:48.936-05:00",
 "logger":"org.springframework.boot.SpringApplication",
 "label":"Application run failed",
 "runtime": {
   "instance":"unknown",
   "clusterName":"unknown",
   "namespace":"unknown",
   "image":"unknown",
   "platformIdentifier":"AJSC7_JERSEY"},
 "application": {
   "deploymentUnitName":"com.att.dmp.ReorgResourceCreatorMs",
   "motsApplicationAcronym":"MOTS_ID"},
 "exception": {
   "exceptionDetails": 
      "Error creating bean with name 'sessionFactory' defined in
       class path resource [com/att/dmp/DBConfiguration.class]: 
       Bean instantiation via factory method failed; nested 
       exception is: org.springframework.beans.BeanInstantiationException: 
       Failed to instantiate
       [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: 
       Factory method 'sessionFactory' threw exception; 
       nested exception is java.lang.NullPointerException",
   "stackTrace":
     "org.springframework.beans.factory.BeanCreationException: 
      Error creating bean with name 'sessionFactory' defined in 
      class path resource [com/att/dmp/DBConfiguration.class]: 
      Bean instantiation via factory method failed; nested exception is 
     org.springframework.beans.BeanInstantiationException: Failed to instantiate
     [org.springframework.orm.hibernate5.LocalSessionFactoryBean]:
     Factory method 'sessionFactory' threw exception; 
     nested exception is java.lang.NullPointerException
       at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:656)
       at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:484)
       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1338)
       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177)
       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:557)
       at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517)
       at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323)
       at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
       at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321)
       at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202)
       at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:860)
       at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:878)
       at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
       at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
       at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
       at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
       at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
       at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
       at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
       at com.att.dmp.Application.main(Application.java:20)
       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.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
   Caused by: org.springframework.beans.BeanInstantiationException:
   Failed to instantiate [org.springframework.orm.hibernate5.LocalSessionFactoryBean]: 
   Factory method 'sessionFactory' 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.instantiate(ConstructorResolver.java:651)
       ... 24 more
   Caused by: java.lang.NullPointerException
       at java.util.Hashtable.get(Hashtable.java:364)
       at org.springframework.core.env.MapPropertySource.getProperty(MapPropertySource.java:42)
       at com.ulisesbocchio.jasyptspringboot.EncryptablePropertySource.getProperty(EncryptablePropertySource.java:13)
       at com.ulisesbocchio.jasyptspringboot.wrapper.EncryptableMapPropertySourceWrapper.getProperty(EncryptableMapPropertySourceWrapper.java:29)
       at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:85)
       at org.springframework.core.env.PropertySourcesPropertyResolver.getProperty(PropertySourcesPropertyResolver.java:62)
       at org.springframework.core.env.AbstractPropertyResolver.getRequiredProperty(AbstractPropertyResolver.java:181)
       at org.springframework.core.env.AbstractEnvironment.getRequiredProperty(AbstractEnvironment.java:556)
       at com.att.dmp.DBConfiguration.sessionFactory(DBConfiguration.java:108)
       at com.att.dmp.DBConfiguration$$EnhancerBySpringCGLIB$$72a5f978.CGLIB$sessionFactory$0(<generated>)
       at com.att.dmp.DBConfiguration$$EnhancerBySpringCGLIB$$72a5f978$$FastClassBySpringCGLIB$$f4df2065.invoke(<generated>)
       at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
       at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
       at com.att.dmp.DBConfiguration$$EnhancerBySpringCGLIB$$72a5f978.sessionFactory(<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)
       ... 25 more"
   }
}

DBConfiguration.Java



import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.core.env.Environment;



@Configuration
@PropertySource("classpath:/propertyLoader/InsertQueries.properties")
@PropertySource("classpath:/propertyLoader/SelectQueries.properties")
@PropertySource("classpath:/propertyLoader/UpdateQueries.properties")

public class DBConfiguration {

    private static Logger logger = LogManager.getLogger(DBConfiguration.class);

    @Value("${spring.datasource.jdbcUrl}")
    private String url;

    @Value("${spring.datasource.username}")
    private String userName;

    @Value("${spring.datasource.password}")
    private String password;

    @Value("${spring.datasource.driver-class-name}")
    private String dbDriverClassName;
    
    @Value("${hibernate.dialect}")
    private String hibernateDialect;
    
    @Value("${hibernate.show_sql}")
    private String hibernateShowSql;
    
    @Value("${hibernate.hbm2ddl.auto}")
    private String hibernateHbm2ddlAuto;
    
    @Value("${entitymanager.packages.to.scan}")
    private String entitymanagerPackagesToScan;
    
      private String PROPERTY_NAME_HIBERNATE_DIALECT = hibernateDialect;
      private String PROPERTY_NAME_HIBERNATE_SHOW_SQL = hibernateShowSql;
      private String PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO = hibernateHbm2ddlAuto;
      private String PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN = entitymanagerPackagesToScan;
      
     @Resource
     private Environment env;

    @Bean(name = "dataSource")
    public DataSource dataSource() {

        logger.info("loading configuration : url : {}, userName ; {}, password ;{}", url, userName, password);
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl(url);
        dataSource.setDriverClassName(dbDriverClassName);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);
        dataSource.setRemoveAbandoned(true);
        dataSource.setInitialSize(10);
        dataSource.setMaxActive(30);
        return dataSource;
    }

    @Bean(name = "jdbcOperations")
    public JdbcTemplate jdbcOperations() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource());
        jdbcTemplate.setFetchSize(500);
        return jdbcTemplate;
    }

    @Bean(name = "jdbcNamedOperations")
    public NamedParameterJdbcTemplate jdbcNamedOperations() {
        NamedParameterJdbcTemplate namedTemplate = new NamedParameterJdbcTemplate(jdbcOperations());
        return namedTemplate;
    }

    
    @Bean (name = "sessionFactory")
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource());
        sessionFactoryBean.setPackagesToScan(env.getRequiredProperty(PROPERTY_NAME_ENTITYMANAGER_PACKAGES_TO_SCAN));
        sessionFactoryBean.setHibernateProperties(hibProperties());
        return sessionFactoryBean;
    }
    
    private Properties hibProperties() {
        Properties properties = new Properties();
        properties.put(PROPERTY_NAME_HIBERNATE_DIALECT, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_DIALECT));
        properties.put(PROPERTY_NAME_HIBERNATE_SHOW_SQL, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_SHOW_SQL));
        properties.put(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO, env.getRequiredProperty(PROPERTY_NAME_HIBERNATE_HBM2DDL_AUTO));
        return properties;  
    }
    
    @Bean(name = "transactionManager") 
    public HibernateTransactionManager transactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }


}

application.properties

#Hibernate Configuration:
hibernate.dialect=org.hibernate.dialect.OracleDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
entitymanager.packages.to.scan=com.att.dmp.entity

CodePudding user response:

You've assigned fields without @Value to those with, and used those in your code instead.

Each of those fields are null and not injected by Springboot

You're then using a null value in env.getRequiredProperty, which throws NPE for null lookups

Solution: don't duplicate fields

Spring properties can reference environment variables, so you shouldn't be doing that in code

For example

hibernate.show_sql=§{HIBERNATE_SHOW_SQL:true} 
  • Related