persistence
persistence copied to clipboard
Allow side-effect free check whether a named query is available
Currently the only way to check whether a named query with a given name exists is calling EntityManager.createNamedQuery(…). Unfortunately the non-presence of a query is expressed by throwing an exception. That in turn causes a transaction currently in progress to be marked as to be rolled back:
Runtime exceptions thrown by the methods of the EntityManager interface other than the LockTimeoutException will cause the current transaction to be marked for rollback if the persistence context is joined to that transaction.
(from section 3.1.1. JPA 2.1 specification.
This means that even if the user code is able to mitigate this scenario, the currently running transaction will be broken. This has come up to be particularly problematic in the context of component systems that lazily instantiate application components (i.e. CDI) as this increases the probability of a business transaction already running when the EntityManager is created and used the first time.
Spring Data JPA currently tries to work around this by creating a dedicated EntityManager for the testing lookup. Also, in Spring environments application components are usually created eagerly so that it's less likely users run into these situations.
We introduced dedicated means to work around this in Spring Data but it seems to me that the fundamental issue – a plain lookup of something rolling back the transaction – is way too aggressive here.
If changing the behavior of EntityManager.createNamedQuery(…) is not an option, maybe providing a new method that allows to check for the presence of a named query could be an option to consider.
- Issue Imported From: https://github.com/javaee/jpa-spec/issues/111
- Original Issue Raised By:@glassfishrobot
- Original Issue Assigned To: @ldemichiel
@glassfishrobot Commented Reported by oliver.gierke
@glassfishrobot Commented neilstockton said: NamedQueryDoesntExistException (extends RuntimeException) sounds like a simple solution for createNamedQuery. I don't see how backwards compatibility is affected with that, and then I can catch problems where I type a query name in wrong!
@glassfishrobot Commented This issue was imported from java.net JIRA JPA_SPEC-111
Instead of addressing this issue directly, I would solve indirectly, as a side-effect of doing something like #505.