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 it can be done:
@Test
public void exists() {
assertFalse(todoRepository.existsById(105L));
assertTrue(todoRepository.existsById(101L));
}
The deleteById() method is used to delete an entity with a specific ID. In the following example, we are deleting one of the todos, reducing the available todos from three to two:
@Test
public void delete() {
todoRepository.deleteById(101L);
assertEquals(2,todoRepository.count());
}
The deleteAll() method is used to delete all the entities managed by the specific repository. In the specific example here, all the todos from the todo table are deleted:
@Test
public void deleteAll() {
todoRepository.deleteAll();
assertEquals(0,todoRepository.count());
}
The save() method can be used to update or insert an entity. The following example shows how the description of a todo can be updated. The following test uses TestEntityManager to flush the data before retrieving it. TestEntityManager is autowired as part of the functionality of @DataJpaTest Annotation:
@Autowired
TestEntityManager entityManager;
@Test
public void save() {
Todo todo = todoRepository.findById(101L).get();
todo.setDescription("Todo Desc Updated");
todoRepository.save(todo);
entityManager.flush();
Todo updatedTodo = todoRepository.findById(101L).get();
assertEquals("Todo Desc Updated",updatedTodo.getDescription());
}