-
Notifications
You must be signed in to change notification settings - Fork 54k
BAEL-5439: PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate #12303
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
Merged
JavierPeris
merged 2 commits into
eugenp:master
from
etrandafir93:features/BAEL-5439-jpa_detached_entity
Jun 26, 2022
Merged
BAEL-5439: PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate #12303
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
46 changes: 46 additions & 0 deletions
46
...ceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/HibernateUtil.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| package com.baeldung.hibernate.exception.detachedentity; | ||
|
|
||
| import java.util.Properties; | ||
|
|
||
| import org.hibernate.SessionFactory; | ||
| import org.hibernate.boot.registry.StandardServiceRegistryBuilder; | ||
| import org.hibernate.cfg.Configuration; | ||
| import org.hibernate.cfg.Environment; | ||
| import org.hibernate.service.ServiceRegistry; | ||
|
|
||
| import com.baeldung.hibernate.exception.detachedentity.entity.Comment; | ||
| import com.baeldung.hibernate.exception.detachedentity.entity.Post; | ||
|
|
||
| public class HibernateUtil { | ||
| private static SessionFactory sessionFactory; | ||
|
|
||
| public static SessionFactory getSessionFactory() { | ||
| if (sessionFactory == null) { | ||
| try { | ||
| Configuration configuration = new Configuration(); | ||
| Properties settings = new Properties(); | ||
| settings.put(Environment.DRIVER, "org.hsqldb.jdbcDriver"); | ||
| settings.put(Environment.URL, "jdbc:hsqldb:mem:transient"); | ||
| settings.put(Environment.USER, "sa"); | ||
| settings.put(Environment.PASS, ""); | ||
| settings.put(Environment.DIALECT, "org.hibernate.dialect.HSQLDialect"); | ||
| settings.put(Environment.SHOW_SQL, "true"); | ||
| settings.put(Environment.FORMAT_SQL, "true"); | ||
| settings.put(Environment.USE_SQL_COMMENTS, "true"); | ||
| settings.put(Environment.HBM2DDL_AUTO, "update"); | ||
| configuration.setProperties(settings); | ||
|
|
||
| configuration.addAnnotatedClass(Comment.class); | ||
| configuration.addAnnotatedClass(Post.class); | ||
|
|
||
| ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()) | ||
| .build(); | ||
| sessionFactory = configuration.buildSessionFactory(serviceRegistry); | ||
|
|
||
| } catch (Exception e) { | ||
| e.printStackTrace(); | ||
| } | ||
| } | ||
| return sessionFactory; | ||
| } | ||
| } |
56 changes: 56 additions & 0 deletions
56
...eptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Comment.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,56 @@ | ||
| package com.baeldung.hibernate.exception.detachedentity.entity; | ||
|
|
||
| import javax.persistence.Entity; | ||
| import javax.persistence.GeneratedValue; | ||
| import javax.persistence.GenerationType; | ||
| import javax.persistence.Id; | ||
| import javax.persistence.ManyToOne; | ||
|
|
||
| @Entity | ||
| public class Comment { | ||
|
|
||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| private Long id; | ||
|
|
||
| private String text; | ||
|
|
||
| public Comment(String text) { | ||
| this.text = text; | ||
| } | ||
|
|
||
| public Comment() { | ||
| } | ||
|
|
||
| @ManyToOne | ||
| private Post post; | ||
|
|
||
| public Long getId() { | ||
| return id; | ||
| } | ||
|
|
||
| public void setId(Long id) { | ||
| this.id = id; | ||
| } | ||
|
|
||
| public String getText() { | ||
| return text; | ||
| } | ||
|
|
||
| public void setText(String text) { | ||
| this.text = text; | ||
| } | ||
|
|
||
| public Post getPost() { | ||
| return post; | ||
| } | ||
|
|
||
| public void setPost(Post post) { | ||
| this.post = post; | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "Comment{" + "id=" + id + ", name='" + text + '\'' + ", post=" + post + '}'; | ||
| } | ||
| } |
44 changes: 44 additions & 0 deletions
44
...exceptions/src/main/java/com/baeldung/hibernate/exception/detachedentity/entity/Post.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,44 @@ | ||
| package com.baeldung.hibernate.exception.detachedentity.entity; | ||
|
|
||
| import javax.persistence.Entity; | ||
| import javax.persistence.GeneratedValue; | ||
| import javax.persistence.GenerationType; | ||
| import javax.persistence.Id; | ||
|
|
||
| @Entity | ||
| public class Post { | ||
|
|
||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| private Long id; | ||
|
|
||
| private String title; | ||
|
|
||
| public Post() { | ||
| } | ||
|
|
||
| public Post(String title) { | ||
| this.title = title; | ||
| } | ||
|
|
||
| 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; | ||
| } | ||
|
|
||
| @Override | ||
| public String toString() { | ||
| return "Post{" + "id=" + id + ", text='" + title + '\'' + '}'; | ||
| } | ||
| } |
105 changes: 105 additions & 0 deletions
105
...src/test/java/com/baeldung/hibernate/exception/detachedentity/DetachedEntityUnitTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,105 @@ | ||
| package com.baeldung.hibernate.exception.detachedentity; | ||
|
|
||
| import com.baeldung.hibernate.exception.detachedentity.entity.Comment; | ||
| import com.baeldung.hibernate.exception.detachedentity.entity.Post; | ||
|
|
||
| import org.assertj.core.api.Assertions; | ||
| import org.hibernate.Session; | ||
| import org.junit.After; | ||
| import org.junit.Before; | ||
| import org.junit.Test; | ||
|
|
||
| import javax.persistence.PersistenceException; | ||
|
|
||
| import java.util.List; | ||
|
|
||
| import static org.assertj.core.api.Assertions.assertThat; | ||
|
|
||
| public class DetachedEntityUnitTest { | ||
|
|
||
| private static Session session; | ||
| private Post detachedPost; | ||
|
|
||
| @Before | ||
| public void beforeEach() { | ||
| session = HibernateUtil.getSessionFactory() | ||
| .openSession(); | ||
| session.beginTransaction(); | ||
| this.detachedPost = new Post("Hibernate Tutorial"); | ||
| session.persist(detachedPost); | ||
| session.evict(detachedPost); | ||
| } | ||
|
|
||
| @After | ||
| public void afterEach() { | ||
| clearDatabase(); | ||
| session.close(); | ||
| } | ||
|
|
||
| @Test | ||
| public void givenDetachedPost_whenTryingToPersist_thenThrowException() { | ||
| detachedPost.setTitle("Hibernate Tutorial for Absolute Beginners"); | ||
|
|
||
| Assertions.assertThatThrownBy(() -> session.persist(detachedPost)) | ||
| .isInstanceOf(PersistenceException.class) | ||
| .hasMessageContaining("org.hibernate.PersistentObjectException: detached entity passed to persist"); | ||
| } | ||
|
|
||
| @Test | ||
| public void givenDetachedPost_whenTryingToMerge_thenNoExceptionIsThrown() { | ||
| detachedPost.setTitle("Hibernate Tutorial for Beginners"); | ||
|
|
||
| session.merge(detachedPost); | ||
| session.getTransaction() | ||
| .commit(); | ||
|
|
||
| List<Post> posts = session.createQuery("Select p from Post p", Post.class) | ||
| .list(); | ||
| assertThat(posts).hasSize(1); | ||
| assertThat(posts.get(0) | ||
| .getTitle()).isEqualTo("Hibernate Tutorial for Beginners"); | ||
| } | ||
|
|
||
| @Test | ||
| public void givenDetachedPost_whenPersistingNewCommentWithIt_thenThrowException() { | ||
| Comment comment = new Comment("nice article!"); | ||
| comment.setPost(detachedPost); | ||
|
|
||
| session.persist(comment); | ||
| session.getTransaction() | ||
| .commit(); | ||
|
|
||
| Assertions.assertThatThrownBy(() -> session.persist(detachedPost)) | ||
| .isInstanceOf(PersistenceException.class) | ||
| .hasMessageContaining("org.hibernate.PersistentObjectException: detached entity passed to persist"); | ||
| } | ||
|
|
||
| @Test | ||
| public void givenDetachedPost_whenMergeAndPersistComment_thenNoExceptionIsThrown() { | ||
| Comment comment = new Comment("nice article!"); | ||
| Post mergedPost = (Post) session.merge(detachedPost); | ||
| comment.setPost(mergedPost); | ||
|
|
||
| session.persist(comment); | ||
| session.getTransaction() | ||
| .commit(); | ||
|
|
||
| List<Comment> comments = session.createQuery("Select c from Comment c", Comment.class) | ||
| .list(); | ||
| Comment savedComment = comments.get(0); | ||
| assertThat(savedComment.getText()).isEqualTo("nice article!"); | ||
| assertThat(savedComment.getPost() | ||
| .getTitle()).isEqualTo("Hibernate Tutorial"); | ||
| } | ||
|
|
||
| private void clearDatabase() { | ||
| if (!session.getTransaction() | ||
| .isActive()) { | ||
| session.beginTransaction(); | ||
| } | ||
| session.createQuery("DELETE FROM Comment") | ||
| .executeUpdate(); | ||
| session.createQuery("DELETE FROM Post") | ||
| .executeUpdate(); | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.