首页 > 解决方案 > 获取 HibernateException:内部连接池已达到其最大大小,当前没有可用的连接

问题描述

我收到 org.hibernate.HibernateException:内部连接池已达到其最大大小,当前没有可用连接!我相信问题是由于不正确的会话处理。任何人都可以提出正确的方法吗?

这是我的服务类。

@Service
public class DataService {

    @Autowired
    private SessionFactory sessionFactory;

    public User createUser(User newUser) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        session.save(newUser);
        session.getTransaction().commit();
        session.close();
        return newUser;
    }

    public User findUser(UUID userId) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        try {
            return session.get(User.class, userId);
        } finally {
            session.close();
        }
    }
}

下面是我的休眠配置。我认为我的配置是正确的。我的 Session 实例化和关闭服务类是错误的。

<!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>
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/rest_database?useSSL=false</property>
        <property name="connection.username">admin</property>
        <property name="connection.password">admin</property>

        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
        <property name="show_sql">true</property>
        <property name="current_session_context_class">thread</property>
        <property name="hbm2ddl.auto">update</property>
        <property name="hibernate.dbcp.initialSize">5</property>
        <property name="hibernate.dbcp.maxTotal">20</property>
        <property name="hibernate.dbcp.maxIdle">10</property>
        <property name="hibernate.dbcp.minIdle">5</property>
        <property name="hibernate.dbcp.maxWaitMillis">-1</property>

        <mapping class="com.in.models.User" />
    </session-factory>

</hibernate-configuration>

标签: javaspringhibernatejpajdbc

解决方案


在我的hibernate.cfg.xml连接池大小为 1。

<property name="connection.pool_size">1</property>

我的数据库查询浏览器(DBeaver)已经连接到我的数据库,因此当我试图保存对象时,它给出了休眠异常 - 没有可用的连接。

当我在hibernate.cfg.xml中将连接池大小增加到 2 时。异常得到解决,因为数据库允许 2 个连接。

<property name="connection.pool_size">2</property>

推荐阅读