Hibernate使用JPA,整合Druid连接池

Hibernate了解

在这里插入图片描述
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 <http://www.gnu.org/licenses/lgpl-2.1.html>.
 */
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.
 * <p/>
 * Implementors might also implement connection pooling.
 * <p/>
 * 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?
	 * <p/>
	 * 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.
	 * <p/>
	 * 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里面实现了这个接口
在这里插入图片描述
源码:

/*
 * 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)

<?xml version="1.0" encoding="UTF-8"?>
<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="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" 
				/> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://192.168.1.200:3306/SSH_Data?useSSL=false&amp;allowPublicKeyRetrieval=true" 
				/> <property name="javax.persistence.jdbc.user" value="root" /> <property 
				name="javax.persistence.jdbc.password" value="123456" /> -->
			<!-- Hibernate配置 -->
			<property name="hibernate.dialect"
				value="org.hibernate.dialect.MySQL8Dialect"></property>
			<property name="hibernate.show_sql" value="true" />

			<!-- Druid连接池配置 -->
			
			<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&amp;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)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
	<session-factory>
		<!-- Hibernate配置 -->
		<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
		<property name="hibernate.show_sql">true</property>
		
		<!-- Druid连接池配置 -->
		<property name="hibernate.connection.provider_class">com.alibaba.druid.support.hibernate.DruidConnectionProvider</property>
		<property name="url"><![CDATA[jdbc:mysql://192.168.1.200:3306/SSH_Data?useSSL=false&allowPublicKeyRetrieval=true]]></property>
		<property name="username">root</property>
		<property name="password">123456</property>
		<property name="driverClassName">com.mysql.cj.jdbc.Driver</property>		
		<property name="filters">stat</property>
		<property name="maxActive">20</property>
		<property name="initialSize">1</property> 
		<property name="maxWait">60000</property> 
		<property name="minIdle">1</property>
		<property name="timeBetweenEvictionRunsMillis">60000</property>
		<property name="minEvictableIdleTimeMillis">300000</property>
		<property name="testWhileIdle">true</property>
		<property name="testOnBorrow">false</property>
		<property name="testOnReturn">false</property>
		<property name="poolPreparedStatements">true</property>
		<property name="maxOpenPreparedStatements">20</property>
		<property name="asyncInit">true</property>
		
		<!-- 实体类导入 -->
		<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设置。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值