I am investigating an issue I have in my Spring Data + Hibernate app. I have found the issue in the logs but I am trying to understand why a hibernate exception org.hibernate.exception.LockAcquisitionException can throw a Spring org.springframework.dao.CannotAcquireLockException?
For exception reporting, I would like my exceptions to be consistent and to throw all Hibernate exceptions. Is this possible?
Caught unhandled exceptionorg.springframework.dao.CannotAcquireLockException: could not update: [com.database.model.MyTable#22791]; SQL [update MyTable set x=1, etc]; nested exception is
org.hibernate.exception.LockAcquisitionException: could not update:[com.database.model.MyTable#22791]# at
org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:246)# at
org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:221)# at
org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:521)# at
org.springframework.transaction.support.AbstractPlatformTr
why a hibernate exception org.hibernate.exception.LockAcquisitionException can throw a Spring org.springframework.dao.CannotAcquireLockException?
It doesn't. The hibernate exception gets caught and then a Spring exception gets thrown.
For exception reporting, I would like my exceptions to be consistent and to throw all Hibernate exceptions. Is this possible?
I'm not sure I understand why this would be more consistent than logging Spring exceptions or actually beneficial at all. All exceptions inherit from Throwable which offers access to its cause, which should be properly set for all Spring exceptions that are caused by other exceptions. So you can certainly navigate the the chain of causes to find the exception that you want to log. You might even find some of the methods in the various Spring Exceptions helpful, for example getMostSpecificCause.
Hibernate's LockAcquisitionException does not throw Spring's CannotAcquireLockException. Any Spring repository annotated with #Repository, which I believe Spring Data repositories innately are, will come with Spring exception translation. This is so your data layer does not leak out and is all wrapped by common Spring exceptions. See Spring's javadocs on PersistenceExceptionTranslator class or on exception translation.
To disable the translation maybe see this thread: How to deactivate Spring Data exception translation
Related
I am using a org.springframework.data.jpa.repository.JpaRepository save method to save an entity. I figure that save method comes from CrudRepository interface. I am calling this save method from a service class.
try {
studentLog = studentsLogRepository.save(studentLog);
} catch (DataIntegrityViolationException dive) {
LOGGER.warn("Constraint violation occurred. Cannot insert the same record twice.", dive);
}
But the problem is DataIntegrityViolationException is not getting caugh in the catch block. Instead I see in the log following.
java.sql.BatchUpdateException: ORA-00001: unique constraint (QA_VPP.UX_TVPPC_TRAN_LOG_1) violated
at oracle.jdbc.driver.OraclePreparedStatement.executeBatch(OraclePreparedStatement.java:10296) ~[ojdbc6-11.2.0.2.0.jar:11.2.0.2.0]
at oracle.jdbc.driver.OracleStatementWrapper.executeBatch(OracleStatementWrapper.java:216) ~[ojdbc6-11.2.0.2.0.jar:11.2.0.2.0]
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297) ~[commons-dbcp-1.3.jar:1.3]
at org.apache.commons.dbcp.DelegatingStatement.executeBatch(DelegatingStatement.java:297) ~[commons-dbcp-1.3.jar:1.3]
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70) ~[hibernate-core-3.6.7.Final.jar:3.6.7.Final]...
and
2016-12-28 10:13:52,655 LL="DEBUG" CR="1_1482920032_407_357_l73q069_VPP" RE="1482920032407" DE="1" TR="tomcat-http--12" LN="o.s.o.j.JpaTransactionManager" Initiating transaction rollback after commit exception
org.springframework.orm.jpa.JpaSystemException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update; nested exception is javax.persistence.PersistenceException: org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:321) ~[spring-orm-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.orm.jpa.DefaultJpaDialect.translateExceptionIfPossible(DefaultJpaDialect.java:121) ~[spring-orm-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517) ~[spring-orm-3.2.9.RELEASE.jar:3.2.9.RELEASE]
at
I even tried catching ConstraintViolationException which did not work. I thought spring data wraps data layer exception to DataAccessException, in this case its subclass DataIntegrityViolationException. Then why is the exception is not getting caught? My service method is not annotated with #Transactional
What is happening is that when calling the method .save(), under the hood Spring is telling the EntityManager to persist the entity, which will be only making it managed and persistent within the persistence context, however changes in your entity may not be immediately synchronized with the DB state (depending on the flush mode of your configuration), so either exceptions are not thrown yet, until flush or commit commands are issued. So you can try to call .saveAndFlush() to enforce DB synchronization. This way exceptions will be thrown immediately.
To further comprehend how Spring handles transaction management, I'll leave a useful link: Transaction Management
exception thrown from Spring exception translation mechanism when dealing with lower level persistence exceptions.
so untill the transaction commits not done , so need to catch outside the scope
Example TODO
Service Class
studentLog = studentsLogRepository.save(studentLog);
Catch at controller class
try {
call student service
} catch (DataIntegrityViolationException dive) {
LOGGER.warn("Constraint violation occurred. Cannot insert the same record twice.", dive);
or Use Global Exception Handler to do the same using controller advice
My Spring/Java web application has #Transactional services that can touch the database:
#Transactional
public class AbstractDBService { ... }
Desired functionality is for any uncaught throwable that propagates up beyond the service layer to cause a rollback. Was a bit surprised this isn't the default behaviour but after a bit of googling tried:
#Transactional(rollbackFor = Exception.class)
This seems to work except when an exception is deliberately swallowed and not rethrown. (The particular case is when an entity is not found. Guess this could be redesigned to not throw an Exception but expect there will inevitably be others - e.g. one that springs to mind is an InterruptedException when using Thread.sleep()). Then Spring complains:
org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is
javax.persistence.RollbackException: Transaction marked as
rollbackOnly
...truncated..
Caused by: javax.persistence.RollbackException: Transaction marked as rollbackOnly
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:58)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
Am I missing something here?... Is there a way to tell Spring to rollback on all uncaught throwables?
If you want to rollback on all uncaught Throwables, you can specify that in the annotation:
#Transactional(rollbackFor = Throwable.class)
By default Spring doesn't rollback for Error subclasses, probably because it seems doubtful once an Error is thrown that the JVM will be in a good enough state to do anything about it anyway, at that point the transaction can just time out. (If you try to rollback when an OutOfMemoryError is raised, the most likely outcome is another OutOfMemoryError.) So you may not gain much with this.
When you mention the case of swallowing an exception, there's no way Spring can be expected to know about it because the exception is not finding its way to Spring's proxy (which is implementing the transactional functionality). This is what happens in your RollbackException example, Hibernate has figured out the transaction needs to rollback but Spring didn't get the memo because somebody ate the exception. So Spring isn't rolling the transaction back, it thinks everything is ok and tries to commit, but the commit fails due to Hibernate having marked the transaction rollback-only.
The answer is to not swallow those exceptions but let them be thrown; making them unchecked is supposed to make it easier for you to do the right thing. There should be an exception handler set up to receive exceptions thrown from the controllers, most exceptions thrown at any level of the application can be caught there and logged.
so the problem is pretty simple:
We are using JSF 2.0 with Primefaces and EJB to handle our application and we have encountered a problem. We have a single #SessionScoped bean in which we store all ours #Stateful Session Beans.
In one case, (when we didn't handle some exceptions from JPA) and there is an exception:
javax.persistence.PersistenceException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.2.0.v20110202-r8913): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "webuser_idwebuser_pk"
Detail: Key (idwebuser)=(6) already exists.
It leads to destruction of one of our #Stateful Session Bean.
So after refreshing the website, when JSF is still working correctly, after filling the form and trying to submit it, by invoking a method from that Bean there is an exception:
javax.ejb.NoSuchObjectLocalException: The EJB does not exist. session-key: 22900a4d007e1f-6dcc714a-0
What is the most problematic, we have to restart and redeploy the application to make it work on the same computer (or web browser) because the JSF's #SessionScoped Bean is somehow kept through cookies or something.
So the solution I guess would be to force the destuction of that #SessionScoped or refresh the session somehow, but actually I have no idea how to do so.
Or what would be a better approach.
Thanks!
To remedy this, you need to be aware about the difference between application- and system exceptions in EJB.
Those roughly correspond to checked and runtime exceptions respectively.
Application exceptions are supposed to be handled by your own code, and will not cause a transaction rollback or the destruction of a bean. System exceptions have the opposite effect and will cause a rollback and the destruction of the EJB bean.
The latter effect is what you are seeing. JPA throws unchecked exceptions, which thus become system exceptions, which thus cause your SFSB to be destroyed. JSF nor CDI managed beans participate in this "system exception" thing, so they will just propagate the exception and will stay alive.
What you probably want is to define a new Exception that you annotate with #ApplicationException and then set its rollback attribute to true. Catch the JPA exception within your SFSB and wrap and rethrow it with your custom exception.
Ok so I've found the answer on my own.
Actually what I've needed was to handle exceptions in JSF view by extending ActionListenerImpl.
The original article is here:
Original
But what I've done was to extend the exception handling with invalidating the HTTP session which, in the end, ended the life of #SessionScoped Managed Bean and leaded to reinjection of SSBs. Like this:
private void gotoErrorPage(MethodExpression expression) {
FacesContext context = FacesContext.getCurrentInstance();
Application application = context.getApplication();
HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
if (session != null) {
session.invalidate();
}
NavigationHandler navHandler = application.getNavigationHandler();
navHandler.handleNavigation(context, null == expression ? null : expression.getExpressionString(), NAV_ERRORPAGE);
context.renderResponse();
}
I am trying to persist the entity with constraint validation,
when invoke persist - there is constraint that thrown and the caller get EjbTransactionRolledbackException...
so I try to call the validation explicit and throw ConstraintViolationException/RuntimeException and still the caller get EjbTransactionRolledbackException...
when I throw MyException extends Exception - the caller get MyException
Even when I call explicit sc.setRollBackOnly it's still happened :(
This shouldn't be the behavior.
what's going on?
Configuration:
Netbeans 6.9.1
Glassfish 3.0.1
JPA 2.0 (EclipseLink)
EJB 3.1
Thanks!!!
#Stateless
public class My {
#PersistenceContext
EntityManager em;
#Resource
Validator validator;
public Order checkout(Order order) {
Set<ConstraintViolation<Order>> set = validator.validate(order, Default.class);
if (!set.isEmpty()) {
sc.setRollbackOnly();
//throw new ConstraintViolationException(new HashSet<ConstraintViolation<?>>(set));
throw new RuntimeException();
}
this.em.persist(order);
}
so I try to call the validation explicit and throw ConstraintViolationException/RuntimeException and still the caller get EjbTransactionRolledbackException...
Providing the full stacktrace might help. Anyway, I wonder how you are calling your EJB and if you're propagating a transaction, in which case throwing a EJBTransactionRolledbackException is the right behavior in case of a system exception. But the following blog post might help:
Constraint violated, transaction rolled back
When using bean validation on JPA
entities within an EJB 3 bean you
would actually get an
EJBTransactionRolledbackException if
there is a constraint violation.
javax.ejb.EJBTransactionRolledbackException: Invalid object at persist time for groups [javax.validation.groups.Default, ]
Caused by: javax.validation.ConstraintViolationException: Invalid object at persist time for groups [javax.validation.groups.Default, ]
This is all nicely according to
specification, but not really
interesting information. You don't
really want to know what happened, you
want to know what went wrong.
So I recommend adding the following to
your ejb-jar.xml:
<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/ejb-jar_3_0.xsd"
version="3.0">
<assembly-descriptor>
<application-exception>
<exception-class>javax.validation.ConstraintViolationException</exception-class>
<rollback>true</rollback>
</application-exception>
</assembly-descriptor>
</ejb-jar>
That way you can directly access your
violations.
Resources
On EJB and application vs system exception:
Best practices in EJB exception handling
16.6. Exceptions and Transactions
On Bean Validation
Constraint violated, transaction rolled back
Just to integrate #Pascal's answer, it is also possible to mark Exception (if it's on your own) with
#javax.ejb.ApplicationException(rollback = true)
public class UncheckedException extends RuntimeException {...}
All I know about this exception is from Spring's documentation and some forum posts with frostrated developers pasting huge stack traces, and no replies.
From Spring's documentation:
Thrown when an attempt to commit a transaction resulted in an unexpected rollback
I want to understand once and for all
Exactly what causes it?
Where did the rollback occur? in the App Server code or in the Database?
Was it caused due to a specific underlying exception (e.g. something from java.sql.*)?
Is it related to Hibernate? Is it related to Spring Transaction Manager (non JTA in my case)?
How to avoid it? is there any best practice to avoid it?
How to debug it? it seems to be hard to reproduce, any proven ways to troubleshoot it?
I found this to be answering the rest of question: https://jira.springsource.org/browse/SPR-3452
I guess we need to differentiate
between 'logical' transaction scopes
and 'physical' transactions here...
What PROPAGATION_REQUIRED creates is a
logical transaction scope for each
method that it gets applied to. Each
such logical transaction scope can
individually decide on rollback-only
status, with an outer transaction
scope being logically independent from
the inner transaction scope. Of
course, in case of standard
PROPAGATION_REQUIRED behavior, they
will be mapped to the same physical
transaction. So a rollback-only marker
set in the inner transaction scope
does affect the outer transaction's
chance to actually commit. However,
since the outer transaction scope did
not decide on a rollback itself, the
rollback (silently triggered by the
inner transaction scope) comes
unexpected at that level - which is
why an UnexpectedRollbackException
gets thrown.
PROPAGATION_REQUIRES_NEW, in contrast,
uses a completely independent
transaction for each affected
transaction scope. In that case, the
underlying physical transactions will
be different and hence can commit or
rollback independently, with an outer
transaction not affected by an inner
transaction's rollback status.
PROPAGATION_NESTED is different again
in that it uses a single physical
transaction with multiple savepoints
that it can roll back to. Such partial
rollbacks allow an inner transaction
scope to trigger a rollback for its
scope, with the outer transaction
being able to continue the physical
transaction despite some operations
having been rolled back. This is
typically mapped onto JDBC savepoints,
so will only work with JDBC resource
transactions (Spring's
DataSourceTransactionManager).
To complete the discussion:
UnexpectedRollbackException may also
be thrown without the application ever
having set a rollback-only marker
itself. Instead, the transaction
infrastructure may have decided that
the only possible outcome is a
rollback, due to constraints in the
current transaction state. This is
particularly relevant with XA
transactions.
As I suggested above, throwing an
exception at the inner transaction
scope, then catching that exception at
the outer scope and translating it
into a silent setRollbackOnly call
there should work for your scenario. A
caller of the outer transaction will
never see an exception then. Since you
only worry about such silent rollbacks
because of special requirements
imposed by a caller, I would even
argue that the correct architectural
solution is to use exceptions within
the service layer, and to translate
those exceptions into silent rollbacks
at the service facade level (right
before returning to that special
caller).
Since your problem is possibly not
only about rollback exceptions, but
rather about any exceptions thrown
from your service layer, you could
even use standard exception-driven
rollbacks all the way throughout you
service layer, and then catch and log
such exceptions once the transaction
has already completed, in some
adapting service facade that
translates your service layer's
exceptions into UI-specific error
states.
Juergen
Scroll a little more back in the log (or increase it's buffer-size) and you will see what exactly caused the exception.
If it happens not to be there, check the getMostSpecificCause() and getRootCause() methods of UnexpectedRollbackException- they might be useful.
Well I can tell you how to reproduce the UnexpectedRollbackException. I was working on my project, and I got this UnexpectedRollbackException in following situation. I am having controller, service and dao layers in my project.
What I did is in my service layer class,
class SomeServiceClass {
void outerTransaction() {
// some lines of code
innerTransaction();
//AbstractPlatformTransactionManager tries to commit but UnexpectedRollbackException is thrown, not here but in controller layer class that uses SomeServiceClass.
}
void innerTransaction() {
try {
// someDaoMethod or someDaoOperation that throws exception
} catch(Exception e) {
// when exception is caught, transaction is rolled back, outer transaction does not know about it.
// I got this point where inner transaction gets rolled back when I set HibernateTransactionManager.setFailEarlyOnGlobalRollbackOnly(true)
// FYI : use of following second dao access is wrong,
try {
// again some dao operation
} catch(Exception e1) {
throw e2;
}
}
}
}
I had this problem with Spring Framework 4 + Java 1.8 for this exception.
I solved it.
😊
I know that runtime exceptions rollbacks.
But in my case, project do not use runtime exceptions.
For example, we have code.
#Transactional
#Service
UserFacadeIml implements UserFacade
{
#Autowired
private UserService userService;
//throws UnexpectedRollbackException
//instead NotRuntimeEx
#Override
public void saveUser(User user)
throws NotRuntimeEx
{
return userService.saveUser(user);
}
}
I solved it, when add "Transactional(rollBackFor=NotRuntimeEx.class)" for facade.
It works, because Spring use proxy for facade and proxy for service.
When transactional rollback, proxy of service send context to facade.
But facade proxy does not understand, why transaction rollback.
#Transactional(rollBackFor=NotRuntimeEx.class)
#Service
UserServiceIml implements UserService
{
#Override
public void saveUser(User user)
throws NotRuntimeEx
{
throw new NotRuntimeEx(user);
}
}