Home > other >  How to update @Entity with Spring Projections?
How to update @Entity with Spring Projections?

Time:10-14

Can I use Spring projections to modify and persist content of existing entities? My goal is to update only a specific field. Any other fields of that row in the database should remain untouched. Is that possible with projections?

Or is a projection always only readonly?

public void update() {
    PersonProjection p = repository.findByLastname("Doe");
    p.setLastname("test");
    repository.save(p); //how can I save only that field?
}

@Entity
public class Person {
   @Id private long id;
   private String firstname, lastname, age;
}

interface PersonProjection {
   String getLastname();
   void setLastname(String lastname);
}

interface PersonRepository extends CrudRepository<Person, Long> {
     PersonProjection findByLastname(String lastname);
}

https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

CodePudding user response:

Short answer, no, you cannot use Spring Data projections for updates.

What you could do instead if you don't want to fetch the entity beforehand is to write custom queries to update certain fields.

You can do the update with JPQL or Native Queries as well.

CodePudding user response:

I quote the following sources to answer your question:

From this :

SQL SELECT corresponds to the "projection" in relational algebra

And this :

The Relational Algebra was introduced by E. F. Codd in 1972. It consists of a set of operations on relations:

PROJECT (π): extracts specified attributes (columns) from a relation. Let R be a relation that contains an attribute X. πX(R) = {t(X) ∣ t ∈ R}, where t(X) denotes the value of attribute X of tuple t.

So projection is only read-only as its name is suggested.

To update just one field , please do it in the normal and correct JPA way which you first get the entity instance , then update its state , and let JPA to figure out how to update it by themselves.

  • Related