Hibernate使用JPA,整合Druid连接池

文章目录

  • Hibernate了解
  • Druid了解
  • Hibernate配置
  • 项目源码
  • 总结

Hibernate了解

Hibernate使用JPA,整合Druid连接池_第1张图片
ps:官方文档说,这个配置是用来获取JDBC连接,只要实现了ConnectionProvider接口

源码:

/*
 * Hibernate, Relational Persistence for Idiomatic Java
 *
 * License: GNU Lesser General Public License (LGPL), version 2.1 or later.
 * See the lgpl.txt file in the root directory or .
 */
package org.hibernate.engine.jdbc.connections.spi;
import java.sql.Connection;
import java.sql.SQLException;

import org.hibernate.service.Service;
import org.hibernate.service.spi.Wrapped;

/**
 * A contract for obtaining JDBC connections.
 * 

* Implementors might also implement connection pooling. *

* Implementors should provide a public default constructor. * * @author Gavin King * @author Steve Ebersole */ public interface ConnectionProvider extends Service, Wrapped { /** * Obtains a connection for Hibernate use according to the underlying strategy of this provider. * * @return The obtained JDBC connection * * @throws SQLException Indicates a problem opening a connection * @throws org.hibernate.HibernateException Indicates a problem otherwise obtaining a connection. */ public Connection getConnection() throws SQLException; /** * Release a connection from Hibernate use. * * @param conn The JDBC connection to release * * @throws SQLException Indicates a problem closing the connection * @throws org.hibernate.HibernateException Indicates a problem otherwise releasing a connection. */ public void closeConnection(Connection conn) throws SQLException; /** * Does this connection provider support aggressive release of JDBC * connections and re-acquisition of those connections (if need be) later? *

* This is used in conjunction with {@link org.hibernate.cfg.Environment#RELEASE_CONNECTIONS} * to aggressively release JDBC connections. However, the configured ConnectionProvider * must support re-acquisition of the same underlying connection for that semantic to work. *

* Typically, this is only true in managed environments where a container * tracks connections by transaction or thread. * * Note that JTA semantic depends on the fact that the underlying connection provider does * support aggressive release. * * @return {@code true} if aggressive releasing is supported; {@code false} otherwise. */ public boolean supportsAggressiveRelease(); }

Druid了解

其实Druid里面实现了这个接口
Hibernate使用JPA,整合Druid连接池_第2张图片
源码:

/*
 * Copyright 1999-2018 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.alibaba.druid.support.hibernate;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.service.spi.Configurable;
import org.hibernate.service.spi.Stoppable;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;

public class DruidConnectionProvider implements ConnectionProvider, Configurable, Stoppable {

    private static final long serialVersionUID = 1026193803901107651L;

    private DruidDataSource   dataSource;

    public DruidConnectionProvider(){
        dataSource = new DruidDataSource();
    }

    @SuppressWarnings("rawtypes")
    @Override
    public boolean isUnwrappableAs(Class unwrapType) {
        return dataSource.isWrapperFor(unwrapType);
    }

    @Override
    public <T> T unwrap(Class<T> unwrapType) {
        return dataSource.unwrap(unwrapType);
    }

    @Override
    public Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    @Override
    public void closeConnection(Connection conn) throws SQLException {
        conn.close();
    }

    @Override
    public boolean supportsAggressiveRelease() {
        return false;
    }

    @SuppressWarnings("rawtypes")
    @Override
    public void configure(Map configurationValues) {
        try {
            DruidDataSourceFactory.config(dataSource, configurationValues);
        } catch (SQLException e) {
            throw new IllegalArgumentException("config error", e);
        }
    }

    @Override
    public void stop() {
        dataSource.close();
    }

}

Hibernate配置

JPA配置 (persistence.xml)


<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
          http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
	version="2.2">
	<persistence-unit name="persistUnitName"
		transaction-type="RESOURCE_LOCAL">
		<properties>
			
			
			<property name="hibernate.dialect"
				value="org.hibernate.dialect.MySQL8Dialect">property>
			<property name="hibernate.show_sql" value="true" />

			
			
			<property name="hibernate.connection.provider_class"
				value="com.alibaba.druid.support.hibernate.DruidConnectionProvider" />
			<property name="url"
				value="jdbc:mysql://192.168.1.200:3306/SSH_Data?useSSL=false&allowPublicKeyRetrieval=true" />
			<property name="username" value="root" />
			<property name="password" value="123456" />
			<property name="driverClassName"
				value="com.mysql.cj.jdbc.Driver" />
			<property name="filters" value="stat" />
			<property name="maxActive" value="20" />
			<property name="initialSize" value="1" />
			<property name="maxWait" value="60000" />
			<property name="minIdle" value="1" />
			<property name="timeBetweenEvictionRunsMillis" value="60000" />
			<property name="minEvictableIdleTimeMillis" value="300000" />
			<property name="testWhileIdle" value="true" />
			<property name="testOnBorrow" value="false" />
			<property name="testOnReturn" value="false" />
			<property name="poolPreparedStatements" value="true" />
			<property name="maxOpenPreparedStatements" value="20" />
			<property name="asyncInit" value="true" />
		properties>
	persistence-unit>
persistence>

SessionFactory配置(hibernate.cfg.xml)



<hibernate-configuration>
	<session-factory>
		
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialectproperty>
		<property name="hibernate.show_sql">trueproperty>
		
		
		<property name="hibernate.connection.provider_class">com.alibaba.druid.support.hibernate.DruidConnectionProviderproperty>
		<property name="url">property>
		<property name="username">rootproperty>
		<property name="password">123456property>
		<property name="driverClassName">com.mysql.cj.jdbc.Driverproperty>		
		<property name="filters">statproperty>
		<property name="maxActive">20property>
		<property name="initialSize">1property> 
		<property name="maxWait">60000property> 
		<property name="minIdle">1property>
		<property name="timeBetweenEvictionRunsMillis">60000property>
		<property name="minEvictableIdleTimeMillis">300000property>
		<property name="testWhileIdle">trueproperty>
		<property name="testOnBorrow">falseproperty>
		<property name="testOnReturn">falseproperty>
		<property name="poolPreparedStatements">trueproperty>
		<property name="maxOpenPreparedStatements">20property>
		<property name="asyncInit">trueproperty>
		
		
		<mapping class="entity.SSHUser" />
	session-factory>
hibernate-configuration>

项目源码

链接:https://pan.baidu.com/s/1uZmynHUyB2GKI_eRZ0rW_Q
提取码:1cu3
复制这段内容后打开百度网盘手机App,操作更方便哦

总结

As an ORM tool, probably the single most important thing you need to tell Hibernate is how to connect to your database so that it may connect on behalf of your application. This is ultimately the function of the org.hibernate.engine.jdbc.connections.spi.ConnectionProvider interface. Hibernate provides some out of the box implementations of this interface. ConnectionProvider is also an extension point so you can also use custom implementations from third parties or written yourself. The ConnectionProvider to use is defined by the hibernate.connection.provider_class setting.

翻译:
作为一个ORM工具,您需要告诉Hibernate最重要的一件事就是如何连接到您的数据库,以便它可以代表您的应用程序进行连接。这最终是org.hibernate.engine.jdbc.connections.spi.ConnectionProvider界面的功能。Hibernate提供了这个接口的一些开箱即用的实现。 ConnectionProvider也是一个扩展点,因此您也可以使用第三方的自定义实现或自己编写。在ConnectionProvider使用由定义hibernate.connection.provider_class设置。

你可能感兴趣的:(Hibernate)