这是indexloc提供的服务,不要输入任何密码
Skip to content

BAEL-5763: Fix the HibernateException: Illegal attempt to associate a collection with two open sessions #18698

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package com.baeldung.hibernate.hibernateexception;

import java.util.List;

import jakarta.persistence.CascadeType;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.OneToMany;

@Entity
public class Author {

@Id
private Long id;

private String name;

@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
private List<Book> books;

public Long getId() {
return id;
}

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

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public List<Book> getBooks() {
return books;
}

public void setBooks(List<Book> books) {
this.books = books;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.baeldung.hibernate.hibernateexception;

import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToOne;

@Entity
public class Book {

@Id
private Long id;

private String title;

@ManyToOne
private Author author;

public Long getId() {
return id;
}

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

public String getTitle() {
return title;
}

public void setTitle(String title) {
this.title = title;
}

public Author getAuthor() {
return author;
}

public void setAuthor(Author author) {
this.author = author;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.baeldung.hibernate.hibernateexception;

import java.util.HashMap;
import java.util.Map;

import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;

public class HibernateUtil {
private static SessionFactory sessionFactory;

public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
Map<String, Object> settings = new HashMap<>();
settings.put("hibernate.connection.driver_class", "org.h2.Driver");
settings.put("hibernate.connection.url", "jdbc:h2:mem:test");
settings.put("hibernate.connection.username", "sa");
settings.put("hibernate.connection.password", "");
settings.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
settings.put("hibernate.show_sql", "true");
settings.put("hibernate.hbm2ddl.auto", "create-drop");

ServiceRegistry standardRegistry = new StandardServiceRegistryBuilder().applySettings(settings)
.build();

Metadata metadata = new MetadataSources(standardRegistry).addAnnotatedClasses(Author.class, Book.class)
.getMetadataBuilder()
.build();

sessionFactory = metadata.getSessionFactoryBuilder()
.build();
}

return sessionFactory;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package com.baeldung.hibernate.hibernateexception;

import static org.assertj.core.api.Assertions.assertThatThrownBy;

import java.util.ArrayList;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.junit.jupiter.api.Test;

class HibernateExceptionUnitTest {

@Test
void whenUsingOneHibernateSession_thenCorrect() {
try (Session session1 = HibernateUtil.getSessionFactory()
.openSession()) {
session1.beginTransaction();

Author author = new Author();
author.setId(2L);
author.setName("Jane Austen");
author.setBooks(new ArrayList<Book>());
session1.persist(author);

Author persistedAuthor = session1.get(Author.class, 2L);

Book newBook = new Book();
newBook.setId(1L);
newBook.setTitle("Pride and Prejudice");
persistedAuthor.getBooks()
.add(newBook);
session1.update(persistedAuthor);

session1.getTransaction()
.commit();
}
}

@Test
void whenUsingMoreThanOneHibernateSessionWithMergeMethod_thenCorrect() {
try (Session session1 = HibernateUtil.getSessionFactory()
.openSession();
Session session2 = HibernateUtil.getSessionFactory()
.openSession()) {
session1.beginTransaction();

Author author = new Author();
author.setId(3L);
author.setName("Leo Tolstoy");
author.setBooks(new ArrayList<Book>());
session1.persist(author);
Author persistedAuthor = session1.get(Author.class, 3L);
session1.getTransaction()
.commit();

session2.beginTransaction();
Book newBook = new Book();
newBook.setId(1L);
newBook.setTitle("War and Peace");
persistedAuthor.getBooks()
.add(newBook);
session2.merge(persistedAuthor);
session2.getTransaction()
.commit();
}
}

@Test
void whenUsingMoreThanOneHibernateSession_thenThrowHibernateException() {
assertThatThrownBy(() -> {
try (Session session1 = HibernateUtil.getSessionFactory()
.openSession();
Session session2 = HibernateUtil.getSessionFactory()
.openSession()) {
session1.beginTransaction();

Author author = new Author();
author.setId(1L);
author.setName("Leo Tolstoy");
author.setBooks(new ArrayList<Book>());
session1.persist(author);
Author persistedAuthor = session1.get(Author.class, 1L);
session1.getTransaction()
.commit();

session2.beginTransaction();
Book newBook = new Book();
newBook.setId(1L);
newBook.setTitle("War and Peace");
persistedAuthor.getBooks()
.add(newBook);
session2.update(persistedAuthor);
session2.getTransaction()
.commit();
}
}).isInstanceOf(HibernateException.class)
.hasMessageContaining("Illegal attempt to associate a collection with two open sessions");
}

}