나는 Hibernate를 배우려고 노력하고 있으며 나는 가장 간단한 Person Entity를 썼다. 나는 그들 중 2000 개를 삽입하려고 시도했다. 나는 더 이상 사용되지 않는 메소드를 사용하고 있다는 것을 알고, 나중에 새로운 것을 알아 내려고 노력할 것입니다.Hibernate에서 너무 많은 연결
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();
}
}
}
내가 잠시 후에 얻을 것은 :
다음@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;
}
}
내가 루프 2000 개체를 삽입하는 작은 응용 프로그램 클래스를 썼다 :
첫째, 여기에 클래스 사람입니다
지금 나는 아마 알고 있지만, 광산에 대한 시험이었다 여러 트랜잭션을 실행할 때 어떤 일이 발생하는지보십시오. 그리고 매번 한 번 열리는 것이 있기 때문에 효과가 있습니다. 나는 커밋 후스레드 "main"에서 예외가 발생했습니다. org.hibernate.exception.JDBCConnectionException : 연결을 열 수 없습니다.
에 의해 발생 : com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException : 나는 일하는 것이 루프 외부 트랜잭션을 넣을 경우 너무 많은 연결
session.close()
을 추가했지만, 나는 스레드에서 "주요"org.hibernate.SessionException을
을 폐쇄되었다 ?예외를 가지고 : 세션이 이미 문제를 해결하는 방법에 따라서
위대한 문제였습니다. 감사합니다. 뒤늦은 견해에서 꽤 명백한 ... 그래서 나중에 나는 그것을 싱글 톤으로 만들 수있다. 또는 나는 최대 절전 모드를 이해 한 후에, [Spring Data] (http://www.springsource.org/spring-news/) 데이터)? – stivlo
@stivlo : 예, Spring 애플리케이션에서 전형적인 접근법은'SessionFactory'를 싱글 톤으로 생성하는 것입니다 (특별한'LocalSessionFactoryBean' 헬퍼 클래스가 있습니다). 스프링 데이터에 대해서는 익숙하지 않다. – axtavt