• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

JPA-Hibernate - EntityExistsException Question

 
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We recently converted our EJB2.1 application to EJB3 (Jboss 4.2.CP07) and landed in to a problem with EntityExistsException Vs DuplicateKeyException (EJB2).
Earlier with EJB2 we were able to do operation like

try{
<EntityHome>.create(<some object>);
} catch (DuplicateKeyException ex) {
Do some other task ..involving database
}

When we converted to EJB3 ..the code looks like below

try{
em.persist(<some PO>);
} catch (EntityExistsException ex) {
Do some other task ..using em

}

In second case we learnt that we couldn't do any more operations on the em as the transaction is closed, is this the expected behavior?
If yes can anyone please suggest a different way to handle these scenarios ?

 
author & internet detective
Posts: 41967
911
Eclipse IDE VI Editor Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You could call findById first and only persist if it returns null. Exceptions are meant for a non-expected path. It sounds like you are expecting the row might be there.

I have this pattern a lot:
findById
if null: insert record
if not null: merge records
 
It will give me the powers of the gods. Not bad for a tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic