CrudRepository

Basic Spring
≈ 2 min read

Ready-made CRUD operations

The CrudRepository interface already contains the main operations that repeat for almost every entity: save an object, find it, retrieve all records, check whether it exists, and delete data. That means basic CRUD often does not require declaring your own methods.

Customer saved = repository.save(customer);

Optional<Customer> customer = repository.findById(42L);
boolean exists = repository.existsById(42L);
long total = repository.count();

repository.deleteById(42L);

findById() returns an Optional because a row with that identifier may not exist. save() returns the saved object — this is especially important when the database generates the identifier during insertion.

When save inserts and when it updates

Before saving, Spring Data JDBC determines whether the object is considered new. For a regular entity with a generated object identifier, the typical case is simple: id == null means a new record, while a populated identifier means an existing one. The library also supports other strategies for determining whether an object is new, so this rule should not be treated as a universal assumption for every model.

save() works with an entity as a persisted whole, not as a “changed field.” You should not expect Spring Data JDBC to track object changes between reads and writes the same way an ORM persistence context does.