Suppose I have some code like this:
Vehicle vehicle = vehicleRepostory.findByIdInitialized(vehicleId);
If the Vehicle
cannot be found this method will return null
. The specification says in this case I must throw a MyObjectNotFoundException
so the code becomes something like this:
Vehicle vehicle = vehicleRepostory.findByIdInitialized(vehicleId);
MyObjectNotFoundException.throwIfNull(vehicle, Vehicle.class, vehicleId);
What can I do if I want to get rid of calls to throwIfNull
. It is not really DRY and a poor design choice anyway. There must be some design pattern unbeknownst to me. I searched on the web but it did not turn up anything really usable.
A straightforward solution might be putting the code into my Repository but I use SpringData for this so it is just an interface:
public interface VehicleRepository extends Repository<Vehicle, Long>
// ...
@Query("select v from Vehicle v LEFT JOIN FETCH v.technicalData td LEFT JOIN FETCH v.registrationData rd"
+ " where v.vehicleId = ?")
Vehicle findByIdInitialized(Long vehicleId);