hibernate 休眠异常:内部连接池已达到其最大大小

fdbelqdn  于 2023-02-09  发布在  其他
关注(0)|答案(2)|浏览(156)

每当我添加'@GeneratedValue'注解到Id字段时,我都会遇到上述问题。请参见下面的代码片段,我使用Hibernate保存实体时使用了该代码片段。

public class HibernateTest {
public static void main(String[] args) {
    Employee emp1 = new Employee();
    emp1.setName("User1");

    try (SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); Session session = sessionFactory.openSession()){
    session.beginTransaction();
    session.save(emp1);
    session.getTransaction().commit();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

}
下面是我的实体类

@Entity
@Table (name = "Employee_Details")
public class Employee {
    @Id  @GeneratedValue(strategy=GenerationType.AUTO)
    private int id;
    private String name;
    public int getId() { return id; }
    public void setId(int id) { this.id = id; } 
    public String getName() {
        return name;
    }
    public void setName(String name) { this.name = name; }
}

在hibernate.cfg.xml中,连接池大小设置为1

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

我每次都关闭会话和sessionFactory示例。仍然在日志中遇到以下异常

org.hibernate.HibernateException: The internal connection pool has reached its maximum size and no connection is currently available!
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections.poll(DriverManagerConnectionProviderImpl.java:322)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:189)
at org.hibernate.internal.NonContextualJdbcConnectionAccess.obtainConnection(NonContextualJdbcConnectionAccess.java:35)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:48)
at org.hibernate.id.enhanced.TableStructure$1.getNextValue(TableStructure.java:125)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)

如果我从ID字段中删除“GeneratedValue”注解,这将正常工作。有人能告诉我,为什么会失败?以及如何解决它?

2ledvvac

2ledvvac1#

我遇到了这个问题,并通过替换解决了它:

@GeneratedValue(strategy = GenerationType.AUTO)

与:

@GeneratedValue(strategy = GenerationType.IDENTITY)

希望对你也有效!

ccrfmcuu

ccrfmcuu2#

我认为它使用连接来确定“id”。也许将连接数设置为2而不是1可以解决问题。

相关问题