4

I am currently using a native query for selecting an entity from the join of multiple tables.

 public interface POrderRepository extends CRUDRepository<POrder, long>

 @Query("SELECT order_a.column_a, order_b.column_b from order_a inner join order_b on order_a.column_x = order_b.column_y")
 ArrayList<POrder> readAllPOrders();

I would like this method to also throw EmptyResultSetDataAccessException, wrapped in a DataAccessException in case nothing is found. As I understand, this is the default behaviour for the CRUD operations provided by CRUDRepository methods such as findall.

How can I go about achieving the same?

shikharraje
  • 127
  • 1
  • 17
  • 4
    Your understanding is wrong. It won't throw an exception it will return an empty list. – M. Deinum Oct 05 '17 at 09:08
  • @M.Deinum Thanks for your response. But, generally, if one wants to trigger exceptions on native queries, is there no way to do so? For instance, when one uses JDBCTemplate with callbacks, one could throw exceptions such as `EmptyResultSetDataAccessException`. – shikharraje Oct 05 '17 at 09:15
  • @araknoid Sure, but, for cleaner code, I was hoping to throw `DataAccessException`s from the Repository layer itself. – shikharraje Oct 05 '17 at 09:16
  • 2
    Why would that be cleaner? An exception should be an exceptional case and you shouldn't use it for control flow. You should be using correct checking (and thus explicit in your code) to do something in a certain case. You shouldn't rely on an exception. – M. Deinum Oct 05 '17 at 09:18
  • So, the way native queries were designed in Spring JPA, the intention was that, wherever used, the programmer had to be explicit to check for these conditions?But how does this work for, say, native `DELETE` queries? Let us say that, we have a native `DELETE` query, and we would want to ensure that the entity to be deleted exists in the table in the first place. Now, usually, wouldn't this be handled by the throwing of an exception, or does this also get explicitly checked? – shikharraje Oct 05 '17 at 09:33
  • @araknoid FYI This is NOT the JPA API. It is Spring Data. Completely different API –  Oct 05 '17 at 09:50

0 Answers0