I would like to update one field in User domain model and I don't want to process whole instance of domain model.
Data for update are represented in UserEncryptionData domain model class. BaseEntity (parent class) holds primary key for User entity - so JPA has all information (IMHO) needed to process the update.
@Entity
@Table(name = "users")
public class UserEncryptionData extends BaseEntity {
@Column(nullable = false, name = "salt", unique = true)
@JsonProperty("salt")
private String salt;
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
}
In UserRepository I would like to update these data:
public interface UserRepository extends BaseRepository<User, UUID> {
User update(UserEncryptionData encryptionData);
// the rest omitted...
}
but Spring complains:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property update found for type User!
Is this way possible to update only subset of domain model fields or do I have to process whole User entity?
You can use the save method on UserEncryptionData object after obtaining it from the database, and modified the fields you need to update and Spring will do the job.
UserEncryptionData user = userRepository.findById("id");
user.setSalt("updated salt");
user.save();
But if you want only to update one field you have to write your own update query using @Modifying and @Query annotations:
@Modifying
@Query("update UserEncryptionData u set u.salt = :salt where u.id = :id")
int setUserById(@Param("salt") String salt, @Param("id") Long id);
https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.modifying-queries
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With