Java /休眠错误:检测到连接泄漏。内部连接池已达到最大大小,并且当前没有可用的连接

时间:2018-08-21 01:39:37

标签: java hibernate

我是Java / Hibernate的新手,也不知道此错误是什么意思。

ERROR: Connection leak detected: there are 1 unclosed connections upon shutting down pool jdbc:mysql://localhost:3306/hb_student_records?useSSL=false&serverTimezone=UTC
Exception in thread "main" org.hibernate.HibernateException: The internal connection pool has reached its maximum size and no connection is currently available!

我在Stack Overflow的其他论坛上查找了答案,但在那里没有任何意义。

我的课程如下:

创建学生演示

package com.rsharma.hibernate.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.rsharma.hibernate.demo.entity.Student;

public class CreateStudentDemo {

    public static void main(String[] args) {

        // create session factory
        SessionFactory factory = new Configuration()
                                .configure("hibernate.cfg.xml")
                                .addAnnotatedClass(Student.class)
                                .buildSessionFactory();

        // create session
        Session session = factory.getCurrentSession();

        try {           
            // create a student object
            System.out.println("Creating new student object...");
            Student tempStudent = new Student("Rishav", "Sharma", "paul@luv2code.com");

            // start a transaction
            session.beginTransaction();

            // save the student object
            System.out.println("Saving the student...");
            session.save(tempStudent);

            // commit transaction
            session.getTransaction().commit();

            System.out.println("Done!");
        }
        finally {
            factory.close();
        }
    }

}

Student.java

package com.rsharma.hibernate.demo.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity 
@Table(name="student")
public class Student {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="id")
    private int id; 

    @Column(name="first_name")
    private String firstName; 

    @Column(name="last_name")
    private String lastName; 

    @Column(name="email")
    private String email; 



    public Student(){ 

    }


    public Student(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }


    public int getId() {
        return id;
    }


    public void setId(int id) {
        this.id = id;
    }


    public String getFirstName() {
        return firstName;
    }


    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }


    public String getLastName() {
        return lastName;
    }


    public void setLastName(String lastName) {
        this.lastName = lastName;
    }


    public String getEmail() {
        return email;
    }


    public void setEmail(String email) {
        this.email = email;
    }


    @Override
    public String toString() {
        return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }

}

还有我的config.xml文件

hibernate.cfg.xml

<!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>

        <!-- JDBC Database connection settings -->
        <property name="connection.driver_class">com.mysql.cj.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/hb_student_records?useSSL=false&amp;serverTimezone=UTC</property>
        <property name="connection.username">hbstudent</property>
        <property name="connection.password">hbstudent</property>

        <!-- JDBC connection pool settings ... using built-in test pool -->
        <property name="connection.pool_size">1</property>

        <!-- Select our SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Echo the SQL to stdout -->
        <property name="show_sql">true</property>

        <!-- Set the current session context -->
        <property name="current_session_context_class">thread</property>

    </session-factory>

</hibernate-configuration>

我不知道是什么原因导致我打开连接,因为我已经关闭班级的工厂并且会话是临时的。

8 个答案:

答案 0 :(得分:2)

我认为您还应该在关闭工厂对象之前冲洗并关闭会话对象。

答案 1 :(得分:1)

它对我不起作用:(

public static void main(String[] args) {

        //craete sessionfactory
        SessionFactory factory = new Configuration().configure("hibernate.cfg.xml").addAnnotatedClass(Student.class).buildSessionFactory();

        //craete session
        Session session = factory.getCurrentSession();


        try {
            //use the seesion to save the object
            System.out.println("Creating the student object ...");
            Student student = new Student("abc","fgh","jklop@gmail.com");
            //start the tranction
            session.beginTransaction();
            //save the student object
            System.out.println("Saving the Student...");
            session.save(student);
            //commit the tranction
            session.getTransaction().commit();
            System.out.println("Commit Done!!");

        }catch(Exception exe) {
            session.flush();
            session.close();
            factory.close();
        }


    }

答案 2 :(得分:0)

在下面的实体类中使用 @GeneratedValue(strategy = GenerationType.IDENTITY)

答案 3 :(得分:0)

此问题的快速解决方法是用旧的Hibernate 5.2 jar文件替换最新的Hibernate软件包。

实际上问题不在于连接池,try and catch块中存在某些对象类型不匹配,您可以删除try and catch块并查看真正的异常是什么。

也许休眠专家可以回答这个问题。

当然,“在关闭工厂对象之前刷新并关闭会话对象”对您没有帮助。

答案 4 :(得分:0)

  • 在学生类的第14行上,您已将ID生成策略声明为@GeneratedValue(strategy = GenerationType.AUTO)。
  • 将其更改为 @GeneratedValue(strategy = GenerationType.IDENTITY)
  • 这将消除错误。
  • 尝试添加其他Student对象并运行。
  • 查看“ Hibernate文档”以查找数据库支持的数据库。
  • 以下是所有4种ID生成策略:
  • GenerationType。自动-为特定数据库选择合适的策略。
  • GenerationType。 IDENTITY -使用数据库标识列分配主键。
  • GenerationType。序列-使用数据库序列分配主键。
  • GenerationType。-使用基础数据库表分配主键以确保唯一性。

答案 5 :(得分:0)

您好,我怀疑您看到删除@GenerationType(Strategy=GeneratedValue.Identity)行, 因为我猜您在主键列中使用了自动递增。 @GenerationType(Strategy=GeneratedValue.Identity)仅在您想在数据库中保存多个对象时使用。

答案 6 :(得分:0)

您应该更改

MainScreen

class MainScreen(Screen):

    def update(self):
        Scanner.change_number()

然后它将起作用。

答案 7 :(得分:0)

为我解决的是为每个事务创建一个新的 EntityManager 并在每个事务之后像这样关闭它。

} finally {
    session.close();
    entityManager.close();
}
相关问题