The findById() method can be used to query using the primary key. The following snippet shows an example:
@Test public void findOne() { Optional<Todo> todo = todoRepository.findById(101L); assertEquals("Todo Desc 1", todo.get().getDescription()); }
Optional represents a container object for an object that can be null. Some of the important methods in Optional are listed below:
- isPresent(): Check if Optional contains a non-null value.
- orElse(): Default value if the object contained is null.
- ifPresent(): Code in ifPresent is executed if the object contained is not null.
- get(): To retrieve the contained object.
The existsById() method can be used to check whether an entity with the given ID exists. The following example shows how ...