This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes EJB and other Java EE Technologies and the fly likes JPA-Hibernate - EntityExistsException Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » EJB and other Java EE Technologies
Bookmark "JPA-Hibernate - EntityExistsException Question" Watch "JPA-Hibernate - EntityExistsException Question" New topic
Author

JPA-Hibernate - EntityExistsException Question

prasanna kumar
Greenhorn

Joined: Jun 27, 2004
Posts: 12
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 ?

Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30057
    
149

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


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: JPA-Hibernate - EntityExistsException Question
 
Similar Threads
EntityExistsException
JPA-Hibernate - EntityExistsException Question
EntityExistsException how to know which key i duplicate?
Hibernate JPA persist() not throwing EntityExistsException
A EJB3 vs EJB2 question