how to utilize HikariCP with Hibernate?

只谈情不闲聊 提交于 2019-12-13 07:36:13

问题


When I used Hibernate itself, I could've done something like Main.getSession().get(User.class, 1); where getSession() would call openSession() from the session factory. but how can I do the same with HikariDataSource? Wiki mentioned something about HikariConnectionProvider but no example was given.

@Bean
public DataSource dataSource() throws SQLException {
    if (dbUrl == null || dbUrl.isEmpty()) {
        return new HikariDataSource();
    } else {
        HikariConfig config = new HikariConfig();
        config.setJdbcUrl(dbUrl);
        return new HikariDataSource(config);
    }
}

回答1:


If I understand you correctly, you want Hibernate to use connection pool provided by Hikari. If that is the case, then SessionFactory has a method setDataSourc(...)

@Bean
public LocalSessionFactoryBean sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    // ...
    return sessionFactory;
}

When you open a session, a connection will be borrowed from Hikari pool.



来源:https://stackoverflow.com/questions/45928255/how-to-utilize-hikaricp-with-hibernate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!