1. Overview

CrudRepository is a Spring Data interface for generic CRUD operations on a repository of a specific type. It provides several methods out of the box for interacting with a database.

In this tutorial, we’ll explain how and when to use the CrudRepository save() method.

To learn more about Spring Data repositories, take a look at our article that compares CrudRepository to other repository interfaces of the framework.

Further reading:

Spring Data JPA @Query

Learn how to use the @Query annotation in Spring Data JPA to define custom queries using JPQL and native SQL.

Spring Data JPA - Derived Delete Methods

Learn how to define Spring Data deleteBy and removeBy methods

2. Dependencies

We’ll have to add Spring Data and H2 database dependencies to our pom.xml file:

<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>

3. Example Application

First, let’s create our Spring Data entity called MerchandiseEntity. This class will define the data types that will get persisted to the database when we call the save() method:

@Entity
public class MerchandiseEntity {
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private double price;

    private String brand;

    public MerchandiseEntity() {
    }

    public MerchandiseEntity(String brand, double price) {
        this.brand = brand;
        this.price = price;
    }
}

Next let’s create a CrudRepository interface to work with the MerchandiseEntity:

@Repository
public interface InventoryRepository 
  extends CrudRepository<MerchandiseEntity, Long> {
}

Here we specify the entity’s class and the entity id’s class, MerchandiseEntity and Long. When an instance of this repository is instantiated, the underlying logic will automatically be in place for working with our MerchandiseEntity class.

So with very little code, we’re already able to start using the save() method.

4. CrudRepository save() to Add a New Instance

Let’s create a new instance of MerchandiseEntity and save it to the database using the InventoryRepository:

InventoryRepository repo = context
  .getBean(InventoryRepository.class);

MerchandiseEntity pants = new MerchandiseEntity(
  "Pair of Pants", BigDecimal.ONE);
pants = repo.save(pants);

Running this will create a new entry in the database table for MerchandiseEntity. Notice that we never specified an id. The instance is initially created with a null value for its id, and when we call the save() method, an id is automatically generated.

The save() method returns the saved entity, including the updated id field.

5. CrudRepository save() to Update an Instance

We can use the same save() method to update an existing entry in our database. Suppose we saved a MerchandiseEntity instance with a specific title:

MerchandiseEntity pants = new MerchandiseEntity(
  "Pair of Pants", 34.99);
pants = repo.save(pants);

Later, we found that we wanted to update the price of the item. We could then simply get the entity from the database, make the change, and use the save() method as before.

Assuming we know the id of the item (pantsId), we can use the CRUDRepository method findById to get our entity from the database:

MerchandiseEntity pantsInDB = repo.findById(pantsId).get(); 
pantsInDB.setPrice(44.99); 
repo.save(pantsInDB);

Here we’ve updated our original entity with a new price and saved the changes back to the database.

We need to keep in mind that calling save() to update an object inside a transactional method is not mandatory.

When we use findById() to retrieve an entity within a transactional method, the returned entity is managed by the persistence provider. So, any change to that entity will be automatically persisted in the database, regardless of whether we are invoking the save() method. Now, let’s create a simple test case to confirm this:

@Test
@Transactional
public void shouldUpdateExistingEntryInDBWithoutSave() {
    MerchandiseEntity pants = new MerchandiseEntity(
      ORIGINAL_TITLE, BigDecimal.ONE);
    pants = repository.save(pants);

    Long originalId = pants.getId();

    // Update using setters
    pants.setTitle(UPDATED_TITLE);
    pants.setPrice(BigDecimal.TEN);
    pants.setBrand(UPDATED_BRAND);

    Optional<MerchandiseEntity> resultOp = repository.findById(originalId);

    assertTrue(resultOp.isPresent());
    MerchandiseEntity result = resultOp.get();

    assertEquals(originalId, result.getId());
    assertEquals(UPDATED_TITLE, result.getTitle());
    assertEquals(BigDecimal.TEN, result.getPrice());
    assertEquals(UPDATED_BRAND, result.getBrand());
}

6. Conclusion

In this brief article, we covered the use of CrudRepository‘s save() method. We can use this method to add a new entry into our database, as well as to update an existing one.

As usual, the code for the article is over on GitHub.

Course – LSD (cat=Persistence)

Get started with Spring Data JPA through the reference Learn Spring Data JPA course:

>> CHECK OUT THE COURSE
res – Persistence (eBook) (cat=Persistence)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.