简体   繁体   English

如何使用 Spring Projections 更新 @Entity?

[英]How to update @Entity with Spring Projections?

Can I use Spring projections to modify and persist content of existing entities?我可以使用 Spring projections来修改和保留现有实体的内容吗? 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 https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections

Short answer, no, you cannot use Spring Data projections for updates.简短的回答,不,您不能使用 Spring Data 投影进行更新。

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.您也可以使用 JPQL 或本机查询进行更新。

I quote the following sources to answer your question:我引用以下来源来回答您的问题:

From this :这个

SQL SELECT corresponds to the "projection" in relational algebra SQL SELECT 对应关系代数中的“投影”

And this :这个

The Relational Algebra was introduced by EF Codd in 1972. It consists of a set of operations on relations:关系代数由 EF Codd 于 1972 年引入。它由一组关系运算组成:

PROJECT (π): extracts specified attributes (columns) from a relation. PROJECT (π):从关系中提取指定的属性(列)。 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.令 R 为包含属性 X 的关系。πX(R) = {t(X) ∣ t ∈ R},其中 t(X) 表示元组 t 的属性 X 的值。

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.只更新一个字段,请按照正常正确的JPA方式进行,首先获取实体实例,然后更新其状态,让JPA自己弄清楚如何更新它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM