Issue
I'm learning java spring. I have to get a user then save the Foo
into the database. The user object is Optional, so I must put the new Foo in ifPresent
then how can I return the result while I can't use let
like javascript?
class="lang-java prettyprint-override"> @PostMapping("/foo")
public ResponseEntity<Foo> createFoo(@Valid @RequestBody Checkout checkout) throws URISyntaxException {
Optional<User> _user = userRepository.findById(userId);
_user.ifPresent(
user->
Foo _foo = checkout.getFoo();
_foo.setUser(user);
Foo foo = checkoutService.saveFoo(_foo );
}
);
return ResponseEntity
.created(new URI("/api/foo/" + foo .getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(foo );```
Solution
You can do something like this:
@PostMapping("/foo")
public ResponseEntity<Foo> createFoo(@Valid @RequestBody Checkout checkout) throws URISyntaxException {
Optional<User> _user = userRepository.findById(userId);
Foo foo = _user.map(user -> {
Foo _foo = checkout.getFoo();
_foo.setUser(user);
return checkoutService.saveFoo(_foo);
}).orElse(null);
return ResponseEntity
.created(new URI("/api/foo/" + foo .getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(foo );
}
the map allows to return another type of object in this case we return the value returned by checkoutService.saveFoo(_foo); and we store it in the foo variable, in case userRepository.findById(userId) returns null, you can use .orElse() as comments @QBrute.
Foo foo = _user.map(user -> {
Foo _foo = checkout.getFoo();
_foo.setUser(user);
return checkoutService.saveFoo(_foo);
}).orElse(<default value>);
Answered By - fneira
Answer Checked By - Robin (JavaFixing Admin)