Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to handle EntityExistsException properly?
    primarykey
    data
    text
    <p>I have two entities: Question and FavoritesCounter. FavoritesCounter should be created when the question is added to favorites for the first time. </p> <p>Consider a use case when two users tries to add a question to favorites simultaneously - this will cause <code>EntityExistsException</code> when <code>entityManager.persist(counter)</code> is called for the second user.</p> <p>But the code below <strong>doesn't work</strong>, because when <code>EntityExistsException</code> is thrown, container marks transaction as <em>rollback only</em> and attempt to return <code>getFavoritesCounter(question)</code> fails with <code>javax.resource.ResourceException: Transaction is not active</code></p> <pre><code>@Stateless public class FavoritesServiceBean implements FavoritesService { ... public void addToFavorites(Question question) { FavoritesCounter counter = getCounter(question); if (counter == null) { counter = createCounter(question); } //increase counter } private FavoritesCounter createCounter(Question question) { try { FavoritesCounter counter = new FavoritesCounter(); counter.setQuestion(question); entityManager.persist(counter); entityManager.flush(); return counter; } catch (EntityExistsException e) { return getFavoritesCounter(question); } } private FavoritesCounter getFavoritesCounter(Question question) { Query counterQuery = entityManager.createQery("SELECT counter FROM FavoritesCounter counter WHERE counter.question = :question"); counterQuery.setParameter("question", question); List&lt;FavoritesCounter&gt; result = counterQuery.getResultList(); if (result.isEmpty()) return null; return result.get(0); } } </code></pre> <p><strong>Question</strong></p> <pre><code>@Entity public class Question implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; //getter and setter for id } </code></pre> <p><strong>FavoritesCounter</strong></p> <pre><code>@Entity public class FavoritesCounter implements Serializable { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @OneToOne @Column(unique = true) private Question question; //getter and setter } </code></pre> <p>What is the best way to return already created entity after <code>EntityExistsException</code>?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload