JpaRepository
A ready-made CRUD interface for JPA
Instead of declaring basic operations manually, a JPA repository usually extends
JpaRepository.
It already contains methods for saving, finding by identifier, checking existence, counting, and deleting entities.
interface CustomerRepository extends JpaRepository<Customer, Long> {
}
@Service
class CustomerService {
private final CustomerRepository repository;
CustomerService(CustomerRepository repository) {
this.repository = repository;
}
Customer rename(long id, String name) {
Customer customer = repository.findById(id).orElseThrow();
customer.setName(name);
return repository.save(customer);
}
}
The interface again has two types: the Customer entity and its Long identifier.
After that, methods such as findById, findAll,
save, existsById, and deleteById are available.
What save means
save is not a persistence system separate from JPA.
For a new entity, Spring Data JPA uses the JPA operation for making it persistent,
and for an entity it considers existing, it uses the JPA state-merging mechanism.
That is why entity lifecycle and persistence-context rules still matter.
Do not call save automatically after every change.
If a managed entity changes inside an appropriate transaction, JPA can detect that change itself.
Transaction boundaries will be covered in detail in a separate section.
Check yourself
Exercise review
The mentor knows the solution and will help you reach it independently
Sign in to use the Mentor
The Mentor uses the current exercise and your conversation history.
Sign in
Review the key nuances and the answer after making your own attempt.
Sign in to view the solution
The solution and explanation are available after signing in.
Sign in