Computer scienceBackendSpring BootSpring Data

CRUD Repositories: Update and Delete

3 minutes read

You have learned the predefined operations from CrudRepository and explored examples for creating and reading. In this topic we will walk through an example for the other two operations: update and delete.

Example setup

First, remember to write the following dependencies:

Maven
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<dependency>
   <groupId>com.h2database</groupId>
   <artifactId>h2</artifactId>
   <scope>runtime</scope>
</dependency>
Gradle - Groovy
dependencies {
  implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
  runtimeOnly 'com.h2database:h2'
  testImplementation 'org.springframework.boot:spring-boot-starter-test'
  //...
}
Gradle - Kotlin
dependencies {
  implementation("org.springframework.boot:spring-boot-starter-data-jpa")
  runtimeOnly("com.h2database:h2")
  //...
}

Of course, you can replace this with any database which suits your needs.

We will continue the example from the first part where you, for instance, decided to open a fitness center and want to store all information about your fitness equipment. So far, we have a Treadmill.

Here's the Entity:

Java
@Entity
public class Treadmill {
    @Id
    private String code;
    private String model;

    // constructors, getters, setters, toString

}
Kotlin
@Entity
class Treadmill(
    @Id
    var code: String,
    var model: String
) {
    override fun toString(): String {
        return "Treadmill(code='$code', model='$model')"
    }
}

And here's how we can define the repository:

Java
public interface TreadmillRepository extends CrudRepository<Treadmill, String> {

}
Kotlin
interface TreadmillRepository : CrudRepository<Treadmill, String>

That's it! This is all we need. Also, here's how we can write an Application runner to print some logs to the console:

Java
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Component
    class Runner implements ApplicationRunner {

        private final TreadmillRepository repository;

        // constructor injection for TreadmillRepository
        Runner(TreadmillRepository treadmillRepository) {
            this.repository = treadmillRepository;
        }

        @PostConstruct
        public void init() {
            repository.save(new Treadmill("aaa", "Yamaguchi runway"));
            repository.save(new Treadmill("bbb", "Yamaguchi runway pro-x"));
            repository.save(new Treadmill("ccc", "Yamaguchi max"));
        }

        @Override
        public void run(ApplicationArguments args) {
            // here's you can print anything for the console
        }

    }

}
Kotlin
@SpringBootApplication
class Application(private val repository: TreadmillRepository) {

    @PostConstruct
    fun init() {
        repository.saveAll(
            listOf(
                Treadmill("aaa", "Yamaguchi runway"),
                Treadmill("bbb", "Yamaguchi runway pro-x"),
                Treadmill("ccc", "Yamaguchi max")
            )
        )
    }

    @Bean
    fun run(): ApplicationRunner {
        return ApplicationRunner {
            // You can print anything to the console here
        }
    }
}

fun main(args: Array<String>) {
    runApplication<Application>(*args)
}

To make the code shorter we will share only the code inside the run() method in the next sections because that will be the only thing changing.

Update

When we print all our treadmills to the output, we realize that the treadmill with the code aaa has the wrong model. It should be Yamaguchi runway-x instead of Yamaguchi runway. Here is how we can fix this:

Java
@Override
public void run(ApplicationArguments args) {
    Treadmill treadmill = repository.findById("aaa").orElseThrow();
    System.out.println("Before update: " + treadmill);
    System.out.println("Updating...");
    treadmill.setModel("Yamaguchi runway-x");
    repository.save(treadmill);
    Treadmill updatedTreadmill = repository.findById("aaa").orElseThrow();
    System.out.println("After update: " + updatedTreadmill);
}
Kotlin
@Bean
fun run(): ApplicationRunner {
    return ApplicationRunner {
        val treadmill = repository.findById("aaa").orElseThrow()
        println("Before update: $treadmill")
        println("Updating...")
        treadmill.model = "Yamaguchi runway-x"
        repository.save(treadmill)
        val updatedTreadmill = repository.findById("aaa").orElseThrow()
        println("After update: $updatedTreadmill")
    }
}

Just a reminder: save methods act as update methods when the database contains an entity with the specified ID.

Before update: Treadmill{code='aaa', model='Yamaguchi runway'}
Updating...
After update: Treadmill{code='aaa', model='Yamaguchi runway-x'}

The output shows that everything is working as expected, and our treadmill model has been updated.

Delete

The CrudRepository interface provides five methods for the delete action. We will cover the deleteById and delete methods. The deleteAllById and deleteAll methods work similarly but for a set of entities. The deleteAll method clears all your entities.

To demonstrate how it works, we introduce a new method:

Java
private void printAllTreadmills() {
    Iterable<Treadmill> treadmills = repository.findAll();
    for (Treadmill treadmill : treadmills) {
        System.out.println(treadmill);
    }
}
Kotlin
private fun printAllTreadmills() {
    val treadmills = repository.findAll()
    for (treadmill in treadmills) {
        println(treadmill)
    }
}

Three types of treadmills are too many. We decide to delete the Yamaguchi max treadmill from our list. It has the code ccc:

Java
@Override
public void run(ApplicationArguments args) {
    System.out.println("Before delete: ");
    printAllTreadmills();

    System.out.println("Deleting...");
    repository.deleteById("ccc");

    System.out.println("After delete: ");
    printAllTreadmills();
}
Kotlin
@Bean
fun run(): ApplicationRunner {
    return ApplicationRunner {
        println("Before delete: ")
        printAllTreadmills()

        println("Deleting...")
        repository.deleteById("ccc")

        println("After delete: ")
        printAllTreadmills()
    }
}
Before delete: 
Treadmill{code='aaa', model='Yamaguchi runway'}
Treadmill{code='bbb', model='Yamaguchi runway pro-x'}
Treadmill{code='ccc', model='Yamaguchi max'}
Deleting...
After delete: 
Treadmill{code='aaa', model='Yamaguchi runway'}
Treadmill{code='bbb', model='Yamaguchi runway pro-x'}

Now there are only two treadmills in the database.

A fitness center is not a new idea. We've got a better one: we will open a co-working center equipped with height-adjustable desks and compact treadmills like the Yamaguchi runway-x. So we need to delete the Yamaguchi runway pro-x as well:

Java
@Override
public void run(ApplicationArguments args) {
    System.out.println("Before delete: ");
    printAllTreadmills();

    System.out.println("Deleting...");
    repository.deleteById("ccc");
    Optional<Treadmill> proXTreadmill = repository.findById("bbb");
    proXTreadmill.ifPresent(repository::delete);

    System.out.println("After delete: ");
    printAllTreadmills();
}
Kotlin
@Bean
fun run(): ApplicationRunner {
    return ApplicationRunner {
        println("Before delete: ")
        printAllTreadmills()

        println("Deleting...")
        repository.deleteById("ccc")
        val proXTreadmill: Optional<Treadmill> = repository.findById("bbb")
        proXTreadmill.ifPresent {
            repository.delete(it)
        }

        println("After delete: ")
        printAllTreadmills()
    }
}
Before delete: 
Treadmill{code='aaa', model='Yamaguchi runway'}
Treadmill{code='bbb', model='Yamaguchi runway pro-x'}
Treadmill{code='ccc', model='Yamaguchi max'}
Deleting...
After delete: 
Treadmill{code='aaa', model='Yamaguchi runway'}

Conclusion

The CrudRepository interface makes implementing database interactions easier by providing predefined methods for creating, reading, updating, and deleting records.

In this topic, we focused on practical examples of the deleting and updating operations.

21 learners liked this piece of theory. 0 didn't like it. What about you?
Report a typo