persistence icon indicating copy to clipboard operation
persistence copied to clipboard

Allow side-effect free check whether a named query is available

Open lukasj opened this issue 10 years ago • 5 comments

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.

lukasj avatar May 21 '15 15:05 lukasj

  • Issue Imported From: https://github.com/javaee/jpa-spec/issues/111
  • Original Issue Raised By:@glassfishrobot
  • Original Issue Assigned To: @ldemichiel

lukasj avatar Aug 31 '18 16:08 lukasj

@glassfishrobot Commented Reported by oliver.gierke

lukasj avatar May 21 '15 15:05 lukasj

@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!

lukasj avatar Nov 29 '16 15:11 lukasj

@glassfishrobot Commented This issue was imported from java.net JIRA JPA_SPEC-111

lukasj avatar May 05 '17 06:05 lukasj

Instead of addressing this issue directly, I would solve indirectly, as a side-effect of doing something like #505.

gavinking avatar Aug 26 '23 08:08 gavinking