我是否正确使用Hibernate与Hikari?

时间:2016-02-21 17:38:53

标签: java hibernate hikaricp

这是我第一次使用hibernate,所以我有一个小问题。 这种使用hibernate 5.1和hikariCP 2.4.3的方法是否正确?

我不确定池是否像这样工作。

我应该打电话给

Session session = sessionFactory.openSession();

Session session = sessionFactory.getCurrentSession();

获得会话? 当我打电话

session.close();

关闭连接或返回池。

线程使用HibernateDataStore来访问db

感谢您的帮助

配置     

<hibernate-configuration>

    <session-factory>
        <property name="hibernate.connection.provider_class">
            org.hibernate.hikaricp.internal.HikariCPConnectionProvider
        </property>
        <property name="hibernate.hikari.dataSourceClassName">
            com.mysql.jdbc.jdbc2.optional.MysqlDataSource
        </property>
        <property name="hibernate.hikari.dataSource.url">
            jdbc:mysql://localhost/xyz
        </property>
        <property name="hibernate.hikari.dataSource.user">user</property>
        <property name="hibernate.hikari.dataSource.password">xyz</property>

        <property name="hibernate.hikari.minimumIdle">20</property>
        <property name="hibernate.hikari.maximumPoolSize">100</property>

        <property name="hibernate.current_session_context_class">
            org.hibernate.context.internal.ThreadLocalSessionContext
        </property>

        <!-- SQL dialect -->
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>

        <!-- Names the annotated entity class -->
        <mapping class="XYZ"/>
    </session-factory>
</hibernate-configuration>

我的DataStore-Class

public class HibernateDataStore implements DataStore {
    private static final Logger logger = LogManager.getLogger();

    /** factory for hibernate sessions */
    private static SessionFactory sessionFactory;

    static {
        setUpHibernate();
    }

    /**
     * set up the hibernate session-factory
     */
    private static void setUpHibernate() {
        logger.debug("building session factory");
        final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
                .configure( "config/server/hibernate.cfg.xml" )
                .build();
        try {
            sessionFactory = new MetadataSources( registry ).buildMetadata().buildSessionFactory();
        }
        catch (Exception e) {
            logger.error("problems building hibernate sessionFactory " + e.getMessage());

            // The registry would be destroyed by the SessionFactory, but we had trouble building the SessionFactory
            // so destroy it manually.
            StandardServiceRegistryBuilder.destroy( registry );
        }
        logger.debug("finished building session factory");
    }


    @Override
    public void storeProduct(Product product) {
        logger.info("storing product: " + product.getTitle());
        Instant start = Instant.now();

        final Session session = sessionFactory.openSession();
        //final Session session = sessionFactory.getCurrentSession();
        session.beginTransaction();
        session.save( product );
        session.getTransaction().commit();
        session.close();

        Instant stop = Instant.now();
        logger.debug("product saved (took " + Duration.between(start, stop).toMillis() + "ms)");
    }
}

1 个答案:

答案 0 :(得分:0)

我认为你应该使用Spring来处理会话工厂

<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource"
    destroy-method="close">
    <constructor-arg ref="hikariConfig" />
</bean>

<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
    <property name="poolName" value="springHikariCP" />
    <property name="connectionTestQuery" value="SELECT 1" />
    <property name="dataSourceClassName"
        value="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" />
    <property name="dataSourceProperties">
        <props>
            <prop key="url">jdbc:mysql://localhost:3306/xyz</prop>
            <prop key="user">root</prop>
            <prop key="password"></prop>
        </props>
    </property>
</bean>

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="packagesToScan" value="com.xyz.model" />
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <!-- <prop key="hibernate.hbm2ddl.auto">update</prop> -->
            <prop key="hibernate.show_sql">false</prop>
            <prop key="hibernate.hikari.dataSource.minimumIdle">5</prop>
            <prop key="hibernate.hikari.dataSource.maximumPoolSize">20</prop>
            <prop key="hibernate.hikari.dataSource.idleTimeout">30000</prop>
        </props>
    </property>
</bean>

<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager"
    p:sessionFactory-ref="sessionFactory">
</bean>