简体   繁体   English

NullPointerException获取休眠会话

[英]NullPointerException getting hibernate session

I am trying to integrate Hibernate 5.2.12 into my Spring application but am getting a nullPointerException when get a session. 我正在尝试将Hibernate 5.2.12集成到我的Spring应用程序中,但是在获取会话时却得到了nullPointerException。

Here is the Hibernate configuration 这是Hibernate配置

@Configuration
@EnableTransactionManagement
public class HibernateConfig {

@Bean
public LocalSessionFactoryBean sessionFactory() {
    System.out.println("Session factory called!");
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setPackagesToScan(
            "com.app.persistence.model");
    sessionFactory.setHibernateProperties(hibernateProperties());

    return sessionFactory;
}

@Bean
public DataSource dataSource() {

    BasicDataSource dataSource = new BasicDataSource();
    dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
    dataSource.setUrl("jdbc:mysql://localhost:3306/appDatabase?useSSL=false");
    dataSource.setUsername("root");
    dataSource.setPassword("password");

    return dataSource;
}

@Bean
public PlatformTransactionManager hibernateTransactionManager() {
    HibernateTransactionManager transactionManager
            = new HibernateTransactionManager();
    transactionManager.setSessionFactory(sessionFactory().getObject());

    return transactionManager;
}

private final Properties hibernateProperties() {
    Properties hibernateProperties = new Properties();
    hibernateProperties.setProperty(
            "hibernate.hbm2ddl.auto", "");
    hibernateProperties.setProperty(
            "hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");

    return hibernateProperties;
}

} }

Here is the my util class where sessionFactory is @AutoWired 这是我的util类,其中sessionFactory为@AutoWired

public class AppHibernateUtil {

private static final AppHibernateUtil instance = new AppHibernateUtil();

@Autowired
private SessionFactory sessionFactory;

public static Session getSession() {

    return getInstance().sessionFactory.openSession();
}

private static AppHibernateUtil getInstance() {
    return instance;
}

} }

Here's my attempted usage of a session 这是我尝试使用的会话

public static String getRoles() {

    System.out.println("Custom: getRoles() called");

    List<RoleEntity> roles = new ArrayList<>();

    try(Session session = AppHibernateUtil.getSession()){

        roles = session.createQuery("from RoleEntity").list();
    }

    return gson.toJson(roles.size());
}

public static void main(String args[]) {
    System.out.println(getRoles());
}

The null exception is thrown here 空异常在这里抛出

return getInstance().sessionFactory.openSession();

This line never gets outputted at the console 此行永远不会在控制台上输出

System.out.println("Session factory called!");

If I ignore the AppHibernateUtil class by creating a test class which injects (or not) the sessionFactory. 如果我通过创建一个注入(或不注入)sessionFactory的测试类来忽略AppHibernateUtil类。 I get the same NPE 我得到相同的NPE

@Component
public class TestController {

private static Gson gson = new Gson();

@Autowired
private static SessionFactory sessionFactory;

public static String getRoles() {

    System.out.println("Custom: getRoles() called");

    List<RoleEntity> roles = new ArrayList<>();

    try(Session session = sessionFactory.getCurrentSession()){

        roles = session.createQuery("from RoleEntity").list();
    }

    return gson.toJson(roles.size());
}

public static void main(String args[]) {
    System.out.println(getRoles());
}
}

Problem is not in your hibernate configuration, but in your dependency injection. 问题不在于您的休眠配置,而在于您的依赖项注入。

You are creating manually singleton of AppHibernateUtil (you are calling new AppHibernateUtil() ), let Spring do its job and annotate AppHibernateUtil with @Component (default scope of component is Singleton), then inject it into you class, where is your session needed. 您正在手动创建AppHibernateUtil的单例(正在调用new AppHibernateUtil() ),让Spring进行其工作并使用@Component注释AppHibernateUtil(组件的默认范围是Singleton),然后将其注入到您的类中,这是您需要进行会话的地方。

My guess is that the NPE is being thrown because the sessionFactory in the getSession() method is null. 我的猜测是,由于getSession()方法中的sessionFactory为null,因此引发了NPE。

This means that Spring is not injecting an instance of SessionFactory . 这意味着Spring不会注入SessionFactory的实例。

That may be because you've chosen to implemented the AppHibernateUtil as a singleton. 那可能是因为您选择将AppHibernateUtil实现为单例。 I won't disgress into a discussion about that, except that's it's relevant to point out that Spring is based on dependency injection and using singletons goes against that approach. 除了要指出的是,Spring是基于依赖项注入的,并且使用单例方式与该方法背道而驰的是,我不会对此进行讨论。

If you want to keep using a singleton, you may have success with additional annotations on the AppHibernateUtil class: 如果要继续使用单例,则可以在AppHibernateUtil类上使用其他注释来获得成功:

@Configuration
@ComponentScan("com.your.package.HibernateConfig")
public class AppHibernateUtil {
...
}

However, as described in the docs , it would probably be best to refactor the AppHibernateUtil class so that it was not a singleton: 但是,如docs中所述,最好重构AppHibernateUtil类,使其不是单例:

@Configuration
public class AppHibernateUtil {
    private final AppConfig appConfig;

    public AppHibernateUtil(AppConfig appConfig) {
         this.appConfig = appConfig;
     }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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