Learning Hibernate: too many connections

Posted by stivlo on Stack Overflow See other posts from Stack Overflow or by stivlo
Published on 2011-11-19T09:38:54Z Indexed on 2011/11/19 9:51 UTC
Read the original article Hit count: 365

Filed under:
|

I'm trying to learn Hibernate and I wrote the simplest Person Entity and I was trying to insert 2000 of them. I know I'm using deprecated methods, I will try to figure out what are the new ones later.

First, here is the class Person:

@Entity
public class Person {

        private int id;
        private String name;

        @Id
        @GeneratedValue(strategy = GenerationType.TABLE, generator = "person")
        @TableGenerator(name = "person", table = "sequences", allocationSize = 1)
        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;
        }

}

Then I wrote a small App class that insert 2000 entities with a loop:

public class App {

        private static AnnotationConfiguration config;

        public static void insertPerson() {
                SessionFactory factory = config.buildSessionFactory();
                Session session = factory.getCurrentSession();
                session.beginTransaction();
                Person aPerson = new Person();
                aPerson.setName("John");
                session.save(aPerson);
                session.getTransaction().commit();
        }

        public static void main(String[] args) {
                config = new AnnotationConfiguration();
                config.addAnnotatedClass(Person.class);
                config.configure("hibernate.cfg.xml"); //is the default already
                new SchemaExport(config).create(true, true); //print and execute
                for (int i = 0; i < 2000; i++) {
                        insertPerson();
                }
        }

}

What I get after a while is:

Exception in thread "main" org.hibernate.exception.JDBCConnectionException: Cannot open connection

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Too many connections

Now I know that probably if I put the transaction outside the loop it would work, but mine was a test to see what happens when executing multiple transactions. And since there is only one open at each time, it should work.

I tried to add session.close() after the commit, but I got

Exception in thread "main" org.hibernate.SessionException: Session was already closed

So how to solve the problem?

© Stack Overflow or respective owner

Related posts about java

Related posts about hibernate