SQL Exception not being caught [message #1172392] |
Tue, 05 November 2013 22:26  |
Eclipse User |
|
|
|
I have a method that inserts in a join table identified in a ManyToMany relationship as follows:
try {
User user = userService.get(id);
user.getGroups().add(newGroup);
} catch (SQLException e) {
log.log(Level.SEVERE, e.getMessage());
} catch (Exception e) {
log.log(Level.SEVERE, e.getMessage());
}
On the database, there is a join table with columns id_user and id_group as primary key.
The code works and when inserting a duplicated record it fails, as expected, with message:
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "user_groups"
Detail: Key (id_user, id_group)=(3, 2) already exists.
But unfortunately, this exception is not being caught on the try/catch, instead it sends 500 and the stack trace to the browser.
What might be happening?
[Updated on: Tue, 05 November 2013 22:29] by Moderator Report message to a moderator
|
|
|
Re: SQL Exception not being caught [message #1173413 is a reply to message #1172392] |
Wed, 06 November 2013 13:59   |
Eclipse User |
|
|
|
This code doesn't show anything that would throw an exception. Assuming you are using JPA, changes to entities will not throw JPA exceptions for the most part. Exceptions only occur when something is issued to the database, such as on transaction commit or EntityManager flush().
|
|
|
Re: SQL Exception not being caught [message #1173449 is a reply to message #1173413] |
Wed, 06 November 2013 14:26   |
Eclipse User |
|
|
|
Thanks for the reply. The exception was occouring after that code, but caused by it, as if the code was being ran on the database after. I fixed it putting a flush right after add(newGroup), but I'm not sure why.
|
|
|
Re: SQL Exception not being caught [message #1173834 is a reply to message #1173449] |
Wed, 06 November 2013 19:48   |
Eclipse User |
|
|
|
Likely the method is wrapped in a transaction that the container will only commit when the method exits. Commit forces the EntityManager to synchronize with the database by flushing SQL statements as mentioned. Flush causes the changes to be pushed to the database earlier.
|
|
|
Re: SQL Exception not being caught [message #1175675 is a reply to message #1173834] |
Thu, 07 November 2013 22:54  |
Eclipse User |
|
|
|
Hi Chris, that makes sense. I am using Java EE 7, and the code above is being called in a JAX-RS rest request (so, request scooped). I don't have fine control of transactions because I use the following code to get the EntityManager instance:
@Produces
@PersistenceContext(type= PersistenceContextType.TRANSACTION)
private EntityManager em;
It is then injected into my service classes. This is how it's done in most tutorials. Would you recommend a different approach, in order to have control of transactions, or is it ok to flush() after entity operations, right before hitting return?
|
|
|
Powered by
FUDForum. Page generated in 0.03554 seconds