java - Getting single NonNull value usgin Spring Data -
i'd have method in repository returns single value. this:
trainingmode findbytrainingnameandnameeng( string trainingname, string nameeng );
http://docs.spring.io/spring-data/data-jpa/docs/current/reference/html/ spring data docs describe in case method can return null if no entity found. i'd throw exception generic message no trainingmode found %trainingname% , %nameeng%
or smth that.
i can use optional<trainingmode>
return value , use orelsethrow
optional<trainingmode> findbytrainingnameandnameeng( string trainingname, string nameeng ); repository.findbytrainingnameandnameeng(name, nameeng).orelsethrow(() -> new runtimeexception(...));
but should call method each time when method called. it's not clear - dry priciple broken.
how nonnull single value orelsethrow using spring data?
the dry principle violated if duplicate null handling throughout application logic being invoked. if dry principle thing worried can think of:
you can make "service" class delegate calls annotated repository , handle null response logic it, , use service class instead of calling repositories directly. drawback introducing layer application (which decouple repositories app logic).
there possibility of adding custom behavior data repositories described in "3.6.1. adding custom behavior single repositories" section of documentation. sorry not posting snippet.
the issue have second approach pollutes app interfaces, enforces follow naming patterns (never liked 'impl' suffixes), , might make migrating code bit more time consuming (when app becomes big becomes harder track interface responsible custom behavior , people start creating own behavior turns out duplicate of another).
Comments
Post a Comment