java - How to handle EntityExistsException properly? -


itemprop = "text">

I have two entities: Questions and preferred contactants When the first time the question is added to the favorite, the preferred contactor should be created.

Consider the case of one use when two users try to add a question in favorites together - this will be caused by EntityExistsException entityManager.persist (counter) is called for another user.

But the code below does not work because when EntityExistsException is thrown, the marker of the container will be sent as Rollback only and attempts to get back getFavoritesCounter (question) fails with javax.resource.ResourceException: Transaction is not active

  @Stateless Public Category Favorite Service Service Free Service Provider {... Public Zero AddToFavorites (Questions Questions) {Favorite Counter Count = GetCounter (Q); If (counter == blank) {counter = createconverter (question); } // rise counter} personal favorite quintetconverter (question question) {try {favoritesCounter counter = new FavoritesCounter (); Counter.setQuestion (question); EntityManager.persist (counter); EntityManager.flush (); Return counter; } Hold (EntityExistsException E) {return getFavoritesCounter (question); }} Private Preferred Quant of FitivetsQuint {Query CounterContact = Unit Manager. Conveyor ("Select Counter for Contact Counter WHERE Counter. Quiz =" Questions "); CounterQuery.setParameter ("question", question); & Lt; FavoritesCounter & gt; Results = countertime.gettslistlist (); If (result.isEmpty ()) empty return; Return result (0); }}  

Question

  @Entii public class questions executes {@Id @ generatedValue (strategy = GenerationType.auto ) Private Long ID; // Sender and Setter for ID}  

Preferred Control

@ Anti-Public Public Segment Active Counter implemented SerialJobs {@Id @GeneratedValue (strategy = generation type AOTO) Private Long ID; @OneToOne @Column (unique = true) Private question question; // getter and setter}

EntityExistsException

back to the previously created unit With the best way to do it, you can make that method in Second Session Bean and mark that method with @TransactionAttribute (REQUIRES_NEW)

. Alternatively, you can take CreateCounter () to the local interface of preferred Seversbeen (also make sure you add @TransactionAttribute (REQUIRES_NEW) annotation) and call it like this:

  @Sateless Public Class Favorsessessben performs favorite service {... @resource secure relationship consistent; Public Zero addToFavorites (Questions Questions) {Favorite Counter Counter = getCounter (Question); If (counter == blank) {counter = session> consort .getBusinessObject (FavoritesService.class) .createCounter (question); } // increase counter} @transaction attribute (REQUIRES_NEW) to create a public-friendly companyContactor (question question) {...} ...}  

to call you instead of business / local interface Need to create_counter () directly so the container knows to start a new transaction.


Comments