Hibernate の Java ベースの構成を使用して sessionFactory Bean を注入すると、Bean が null になり、その理由がわかりません。インターネットで答えを探しましたが、何も見つかりませんでした。構成を調べて、オンラインのガイドと比較しました。どんな答えでも大歓迎です。
ここに正確なエラーがあります
スレッド「メイン」での例外 java.lang.NullPointerException: 「com.example.demo.DemoApplication.sessionFactory」が null であるため、「org.hibernate.SessionFactory.getCurrentSession()」を呼び出せません
これが私のコードです
HibernateConfiguration ファイル、注釈ベース。
@Configuration
@EnableTransactionManagement
public class HibernateConfig {
@Bean
@Scope //By default the scope is singleton which means that the IOC will only create a single instance of the bean and return that one reference for subsequent calls for that bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan( packagesToScan()); //Model packages to scan
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
//Direct Physical Connection Information
@Bean
public DataSource dataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/demo");
dataSource.setUsername("root");
dataSource.setPassword("password");
return dataSource;
}
@Bean
public PlatformTransactionManager hibernateTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
//List of Entities to scan
@Bean
public String [] packagesToScan() {
return new String [] { "com.example.demo.Entities.Student" };
}
//Configures properties of our hibernate configuration, dialect,
private final Properties hibernateProperties() {
Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create");
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5Dialect");
hibernateProperties.setProperty("show_sql", "true");
hibernateProperties.setProperty("current_session_context_class", "thread");
return hibernateProperties;
}
}
セッション ファクトリ シングルトン Bean を使用するために注入しようとしているメイン アプリケーション。
@SpringBootApplication
public class DemoApplication {
@Autowired
static SessionFactory sessionFactory;
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AnimalConfig.class, HibernateConfig.class); // Makes the sessionFactory bean known to the IOC
Session currentSession = sessionFactory.getCurrentSession();
(( ConfigurableApplicationContext )ctx).close(); //Close the applicationContext
SpringApplication.run(DemoApplication.class, args);
}
}