Mr.Decent
Mr.Decent

Reputation: 1

Spring boot 2.1 and Hibernate 5.3 SessionFactory not Autowired when annotating the Dao classes with @Repository

When I am auto wiring hibernate session factory in a Dao implementation annotated with @Repository spring annotation it fails to create the SessionFactory and Dao bean but, it works without the @Repository annotation.

I search through lot of questions and answers but all are related to the earlier version of hibernate and spring boot like unwrap and create a session factory bean but all those methods are not compatible with spring-boot 2.1 and the latest Hibernate version.

are there any specific method to create and autowired a hibernate session factory in spring boot 2.1 and latest hibernate versions(5.3)?

@Repository
public class UserDaoImpl implements UserDao {

    @Autowired
    private SessionFactory sf;

    @Override
    public void addUser(User user) {
        Session session = sf.getCurrentSession();
        session.save(user);
    }


}

in the above code SessionFactory auto-wired without @Repository and I create a config class with a bean as below

@Configuration
public class DataConfig {
    @Bean
    public SessionFactory sessionFactory(@Autowired EntityManagerFactory factory) {
            if (factory.unwrap(SessionFactory.class) == null) {
                throw new NullPointerException("factory is not a hibernate factory");
            }
            return factory.unwrap(SessionFactory.class);
    }

}

It course "The dependencies of some of the beans in the application context form a cycle:" error

Upvotes: 0

Views: 1701

Answers (1)

Muhammad Waqas
Muhammad Waqas

Reputation: 367

@Bean
public SessionFactory sessionFactory() {
    LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource());
    sessionBuilder.scanPackages("com.your.domain.package");
    return sessionBuilder.buildSessionFactory();
}

@Bean
public DataSource dataSource() {
    final HikariConfig config = new HikariConfig();
    config.setMinimumIdle(Integer.valueOf(env.getProperty("spring.datasource.minimumIdle")));
    config.setMaximumPoolSize(Integer.valueOf(env.getProperty("spring.datasource.maximumPoolSize")));
    config.setIdleTimeout(Integer.valueOf(env.getProperty("spring.datasource.idleTimeout")));
    config.setConnectionTestQuery("SELECT 1");
    config.setDataSourceClassName(env.getProperty("spring.datasource.className"));
    config.addDataSourceProperty("url", env.getProperty("spring.datasource.url"));
    config.addDataSourceProperty("user", env.getProperty("spring.datasource.username"));
    config.addDataSourceProperty("password", env.getProperty("spring.datasource.password"));
    return new HikariDataSource(config);
}

@Mr. Decent , change your configuration this way in order to solve this problem.

Upvotes: 0

Related Questions