Spring Data Update

Updating an entity with the JPARepository requires 2 trips to the database. First, you need to fetch the database record, update it with your new values. Then second, you will need to update the database record. This is very simple to do using JPARepository.

@Data
@AllArgsConstructor
@NoArgsConstructor
@JsonInclude(value = Include.NON_NULL)
@Entity
@Table(name = "user")
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", nullable = false, updatable = false, unique = true)
    private Long id;
    
    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    @Column(name = "phone_number")
    private String phoneNumber;
    
    @Column(name = "gender")
    private String gender;

    @Column(name = "date_of_birth")
    private LocalDate dateOfBirth;
    
    public User(Long id) {
        this.id = id;
    }
    
    
}
public interface UserRepository extends JpaRepository<User, Long>{

}

Use JpaRepository.saveAndFlush() method

The JpaRepository.saveAndFlush() method can be used to create or update and entity in the database. If the entity id(@Id) is null or the id specified is not found in the table then JPA will create a new record with a new id. If id is not null and is found in the table then JPA will update the table record with new values passing in.

@Service
@Slf4j
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User signUp(User user) {
        log.info("signup...");
        return userRepository.saveAndFlush(user);
    }
}

Use @Modifying and @Transactional

There is a way to avoid the 2 trips to the database which can be expensive at times especially if your entity has other entities within it. You can image that loading an entity of that kind will be expensive due to JPA having to load child entities. To do this, you use @Modifying and @Transactional.

public interface UserRepository extends JpaRepository<User, Long> {

    @Modifying
    @Transactional
    @Query("update User u set u.deleted = true where u.id = :id")
    Integer softDeleteById(@Param("id") Long id);
}

 




Subscribe To Our Newsletter
You will receive our latest post and tutorial.
Thank you for subscribing!

required
required


Leave a Reply

Your email address will not be published. Required fields are marked *