Labs ICT
Pro Login

CRUD Operations

Create, Read, Update, and Delete.

CRUD Operations

CRUD stands for Create, Read, Update, Delete. These are the four basic operations you'll perform on any database. Spring Data JPA makes all of them incredibly simple.

With just a few lines of code, you can save new records, fetch existing ones, update them, and remove them. No raw SQL required. Let's walk through each operation.

Create with save()

To create a new record, call the save() method. Pass it a new entity object and Spring handles the INSERT statement. The method returns the saved entity with the generated ID.

Here's the cool part. Save works for both creating and updating. If the entity has no ID or the ID doesn't exist in the database, it creates a new row. If the ID already exists, it updates the existing row. One method, two purposes.

User newUser = new User();
newUser.setName("Alice");
newUser.setEmail("alice@example.com");

User savedUser = userRepository.save(newUser);
System.out.println("Created user with ID: " + savedUser.getId());

Read with findById and findAll

To read data, you have two main options. findById() gets a single record by its ID. It returns an Optional<User> so you don't have to worry about null pointers.

findAll() returns every record in the table. Use it when you need a list of all entities. Both methods are straightforward and handle all the database logic behind the scenes.

Optional<User> user = userRepository.findById(1L);
user.ifPresent(u -> System.out.println(u.getName()));

List<User> allUsers = userRepository.findAll();
allUsers.forEach(u -> System.out.println(u.getEmail()));

Update and Delete

Updating an entity is just saving it again. Fetch the entity, change its fields, and call save(). Spring generates an UPDATE statement. Simple and clean.

To delete, call deleteById() with the entity's ID. The record is removed from the database. You can also delete by passing the entity object directly with delete().

Optional<User> existing = userRepository.findById(1L);
if (existing.isPresent()) {
    User user = existing.get();
    user.setName("Alice Updated");
    userRepository.save(user);
}

userRepository.deleteById(1L);
Try it Yourself →