Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an aspect to catch an exception and return null instead

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?

like image 373
Vojtěch Avatar asked May 28 '26 20:05

Vojtěch


2 Answers

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.

like image 117
ndeverge Avatar answered May 31 '26 11:05

ndeverge


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.

like image 39
Jose Luis Martin Avatar answered May 31 '26 10:05

Jose Luis Martin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!