Return "blank" entity if entity does not exist using QueryBuilder

78 Views Asked by At

I would like to be able to return a "DefaultEntity" if the query created by QueryBuilder does not exist, example :

myDao.queryBuilder().where(MyEntityDao.Properties.Id.eq(100)).unique()

If there is no entity with such ID (in this case 100), I don't want to generate an exception, but rather return an Entity that contains some default information.

The use case here is that we have a mobile application that has data stored in the local database that could not be up-to-date compared to data contained in a server, so when I want to display an information from a relation of an Entity, this could lead to a crash when calling toString() afterwards.

I checked the documentation and all over StackOverflow and found these options, but none suits my use case for the following reasons :

  • Surrounding with try/catch blocks : There is A LOT of lines where I would need to do that, I wanted something generic
  • Creating a default entity : This doesn't really resolve the problem as I would need to try/catch anyway
  • Using uniqueOrThrow() : This would generate a DaoException, but then I wasn't able to return something by default, I can just catch that kind of Exception in a custom ExceptionHandler but nothing else

An example of solution would be to override calls to unique() for example, so I could try/catch in a single place of the code and return an Entity following the type I am querying.

Any ideas ?

0

There are 0 best solutions below