I want to use this code in Spring application and Hibernate using JNDI.
@Configuration
@EnableTransactionManagement
public class ContextDatasource {
@Bean
public LocalSessionFactoryBean getSessionFactory() throws NamingException {
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 getHibernateTransactionManager() throws NamingException {
final HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(getSessionFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor getExceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
@Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
try {
transactionManager.setSessionFactory(getSessionFactory().getObject());
} catch (NamingException e) {
e.printStackTrace();
}
return transactionManager;
}
private final Properties hibernateProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", "create-drop");
hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MariaDBDialect");
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.format_sql", "true");
return hibernateProperties;
}
}
When I try to use:
@Autowired
SessionFactory sessionFactory;
..
session = sessionFactory.getCurrentSession();
Session factory is always null. Am I'm missing some important configuration. During package deployment I don't get error messages:
20:15:37,217 INFO [org.hibernate.Version] (ServerService Thread Pool -- 178) HHH000412: Hibernate Core {5.3.1.Final}
20:15:37,219 INFO [org.hibernate.cfg.Environment] (ServerService Thread Pool -- 178) HHH000206: hibernate.properties not found
20:15:37,302 INFO [org.hibernate.annotations.common.Version] (ServerService Thread Pool -- 178) HCANN000001: Hibernate Commons Annotations {5.0.3.Final}
20:15:37,404 INFO [org.hibernate.dialect.Dialect] (ServerService Thread Pool -- 178) HHH000400: Using dialect: org.hibernate.dialect.MariaDBDialect
20:15:37,599 INFO [org.hibernate.orm.beans] (ServerService Thread Pool -- 178) HHH10005002: No explicit CDI BeanManager reference was passed to Hibernate, but CDI is available on the Hibernate ClassLoader.
20:15:38,186 INFO [stdout] (ServerService Thread Pool -- 178) Hibernate:
Can you give me some advice what I'm missing?