java.lang.NullPointerException调用数据源

时间:2018-07-08 14:29:29

标签: java spring hibernate spring-boot

我有要用于存储Hibernate模型的库模块。我问我要使用Spring WAR软件包。

春季主战:

@Configuration
@EnableTransactionManagement
public class ContextDatasource {

    @Bean
    public LocalSessionFactoryBean sessionFactory() throws NamingException {
        final LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "org.plugin.database.models" });
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    public DataSource dataSource() throws NamingException {
        return (DataSource) new JndiTemplate().lookup("java:/global/production_gateway");
    }

    @Bean
    public PlatformTransactionManager hibernateTransactionManager() throws NamingException {
        final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionFactory().getObject());
        return transactionManager;
    }

    @Bean
    public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
        return new PersistenceExceptionTranslationPostProcessor();
    }

    private final Properties hibernateProperties() {
        final Properties hibernateProperties = new Properties();
        return hibernateProperties;
    }
}

库DAO:

public class BlacklistsDaoHibernate implements BlacklistsDao {

    Session session;

    @Autowired
    SessionFactory sessionFactory;

    public BlacklistsDaoHibernate() {
        session = sessionFactory.getCurrentSession();
    }

    @Override
    public void saveOrUpdate(BlacklistsModel blacklistsModel) throws Exception {
        try {
            session.getTransaction().begin();
            session.saveOrUpdate(blacklistsModel);
            session.getTransaction().commit();
        } catch (Exception e) {
            e.printStackTrace();
            session.getTransaction().rollback();
            throw new Exception("Error");
        }
    }

但是我在session = sessionFactory.getCurrentSession();这一行得到了NPE

使用sessionFactory进入Library Jar模块的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以使用@PostConstruct或构造函数注入。 Spring实例化您的对象,然后 then 解析其@Autowired字段。您可以要求它在通过构造函数注入实例化对象之前解决对象的依赖性。

使用构造函数注入:

SessionFactory sessionFactory;
Session session;
public BlacklistsDaoHibernate(@Autowired SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
    this.session = sessionFactory.getCurrentSession();
}

使用@PostConstruct:

@Autowired
SessionFactory sessionFactory;
Session session;

@PostConstruct
void init() {
    this.session = sessionFactory.getCurrentSession();
}

编辑:如果您的目标只是解决注释中提到的NullPointerException,请改用此方法:

@PostConstruct
void init() {
    this.session = sessionFactory.openSession();
}

https://www.java2novice.com/hibernate/session-factory有一个SessionFactory典型用法的示例。