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

时间:2018-10-18 19:30:19

标签: java hibernate

每当我向ID字段添加“ @GeneratedValue”注释时,我都面临上述问题。 请参阅下面的代码片段,我已使用它们使用休眠功能保存实体。

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类

@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'注释,则可以正常工作。谁能告诉我,为什么会失败?以及如何解决?

2 个答案:

答案 0 :(得分:1)

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

@GeneratedValue(strategy = GenerationType.AUTO) 

具有:

@GeneratedValue(strategy = GenerationType.IDENTITY)

希望它也对您有用!

答案 1 :(得分:0)

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