3

I've switched from using Spring Data JPA for regular DAO objects with Entity Manager and found out, that instead of returning null the .getSingleResult() throws NoResultException. Is there some way of adding an aspect that would surround all the DAO function with Try {} Catch{} and return null instead of NoResultExceptions?

Or is there some other way of forcing my DAO objects to return null instead of exceptions without manually surrounding all of them?

Vojtěch
  • 11,312
  • 31
  • 103
  • 173
  • the answer is in this thread: http://stackoverflow.com/questions/1579560/why-in-jpa-entitymanager-queries-throw-noresultexception-but-find-does-not – K.C. Feb 15 '12 at 07:26
  • thanks, but they solve different kind of problem - my problem is changing the behaviour generally, I don't want to write try and catch in each database method. – Vojtěch Feb 15 '12 at 07:55

2 Answers2

3

If I were you, I'd implement another Entity Manager (which inherits from the default one), and I'd override the getSingleResult() with a try/catch in order to return null.

Then, I'll inject my new Entity Manager to my Spring context.

ndeverge
  • 21,378
  • 4
  • 56
  • 85
  • Thanks, that sound reasonable. – Vojtěch Feb 15 '12 at 08:26
  • Actually the inheriting of the default manager will help me solve some other issues. On the other hand, I am using LocalContainerEntityManagerFactoryBean to create the EntityManager - what would be the best way to inherit the EM? Inherit the Factory as well? Or can I inject my inherited class into it? – Vojtěch Feb 15 '12 at 20:13
  • Actually, what is the advantage of using the factory? – Vojtěch Feb 15 '12 at 20:16
  • According to the [doc](http://static.springsource.org/spring/docs/2.5.3/api/org/springframework/orm/jpa/LocalContainerEntityManagerFactoryBean.html), Maybe you'll have to create your own `LocalContainerEntityManagerFactoryBean` and override the [getEntityManagerInterface() method](http://static.springsource.org/spring/docs/2.5.3/api/org/springframework/orm/jpa/AbstractEntityManagerFactoryBean.html#getEntityManagerInterface()). I never did it, but it's worth a try :) – ndeverge Feb 16 '12 at 08:05
2

Add an AroundAvice to execution of your DAO interface, catch the NRE and return null. Is more easy, will work with any JPA implementation and don't break the JPA specifaction that forces a Query interface to throw a NRE when no results are found.

Jose Luis Martin
  • 10,459
  • 1
  • 37
  • 38