How to Use save() Method in Spring Boot with Spring Data JPA
In Spring Boot, use the
save() method from a Spring Data JPA repository to insert a new entity or update an existing one in the database. You call save(entity) on your repository interface, which handles the persistence automatically.Syntax
The save() method is part of Spring Data JPA's CrudRepository or JpaRepository interfaces. It takes an entity object as a parameter and returns the saved entity.
- repository.save(entity): Saves or updates the entity in the database.
- entity: The object representing a database row, annotated with
@Entity. - The method returns the saved entity, which may include updated fields like generated IDs.
java
<S> save(<S> entity);
Example
This example shows a simple Spring Boot application saving a User entity using a UserRepository that extends JpaRepository. It demonstrates creating a new user and saving it to the database.
java
import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; @SpringBootApplication public class SaveExampleApplication implements CommandLineRunner { private final UserRepository userRepository; public SaveExampleApplication(UserRepository userRepository) { this.userRepository = userRepository; } public static void main(String[] args) { SpringApplication.run(SaveExampleApplication.class, args); } @Override public void run(String... args) { User user = new User(); user.setName("Alice"); user.setEmail("alice@example.com"); User savedUser = userRepository.save(user); System.out.println("Saved user with ID: " + savedUser.getId()); } } @Entity class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; private String email; // Getters and setters public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } @Repository interface UserRepository extends JpaRepository<User, Long> { }
Output
Saved user with ID: 1
Common Pitfalls
Some common mistakes when using save() include:
- Not annotating the entity class with
@Entity, so Spring Data cannot map it to a database table. - Forgetting to set the ID field properly or using a wrong generation strategy, causing errors or duplicate entries.
- Assuming
save()only inserts; it also updates if the entity has an existing ID. - Not handling transactions properly, which can cause data inconsistencies.
java
/* Wrong: Missing @Entity annotation */ class User { private Long id; private String name; } /* Right: Add @Entity and @Id annotations */ @Entity class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; }
Quick Reference
| Method | Description |
|---|---|
| save(entity) | Inserts or updates the given entity in the database. |
| saveAll(entities) | Saves all given entities in batch. |
| findById(id) | Retrieves an entity by its ID. |
| delete(entity) | Deletes the given entity from the database. |
Key Takeaways
Use repository.save(entity) to insert or update entities in Spring Boot.
Ensure your entity class is annotated with @Entity and has a proper @Id field.
save() returns the saved entity, often with generated IDs filled in.
save() updates if the entity has an existing ID, inserts if not.
Handle transactions to maintain data consistency when saving.