users@glassfish.java.net

Re: How to catch Internal Exception

From: <glassfish_at_javadesktop.org>
Date: Thu, 21 Jun 2007 12:15:11 PDT

You mean besides doing an em.find() on the object first to ensure it does not exist before you do the em.persist() on the new object?

This is actually a problem in a more sinister way than you may think.

Many folks, with good reason, will simply INSERT a row in the DB, and check the status to see if it's duplicate. They do this rather than the select/insert duo because a) it's faster, b) the result is the same in the short run, and c) it's atomic. With the select/insert duo, someone could (potentially) insert the row between the select and insert if it doesn't exist. Depends on the application as to whether that's important or not.

However, the problem with using the EnityManager is that the exception you get also obliterates the transaction you're in. So, you can't simply "let's persist the row anyway, and then we'll do this other stuff" because the exception kills the transaction and nothing else will work.

I DO NOT KNOW if using an EQL statement to try and insert the row first kills the transaction or not. A direct SQL call certainly won't, you can trap that exception. An EQL call MIGHT work, but I don't know.

So:
a) you can't stop the exception, because it IS an exception. "Don't do that".
b) try checking first to see whether you should be persisting or merging by looking up the object.
c) try using EQL or SQL to ensure your row is created before letting the EM find out the hard way.
[Message sent by forum member 'whartung' (whartung)]

http://forums.java.net/jive/thread.jspa?messageID=223388