繁体   English   中英

Jpa Repository save() 不更新现有数据

[英]Jpa Repository save() doesn't update existing data

我正在尝试更新数据,据我所知,如果 id 为空,save() 方法会保存实体,或者如果在 DB 中找到给定的 id,则更新数据库中的现有实体。

但是,当我尝试保存数据时,它不会更新:

public Employer update() {
    Employer emp = Employer.builder()
        .id(2L) // it exists in database
        .name('new company name')
        .build();

    return repository.save(emp);
}

但是,当我从数据库中检索数据并更新其字段并再次保存时,它会更新:

public Employer update() {
    Employer emp = repository.getOne(2L);
    emp.setName('new company name');

    return repository.save(emp);
}

谁能解释这种行为的原因? 我阅读了文档,但找不到与此相关的任何内容。

这是我的存储库:

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface Employer extends JpaRepository<Employer, Long> {

}

和实体:

@Data
@Entity
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(schema = "public", name = "employer")
public class Employer {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Long id;

  @NotBlank
  @Size(max = 50)
  private String name;

}

您的实体Employer看起来处于分离/瞬态状态,并且您正在手动传递id值,这是不允许的,因为它被标记为@GeneratedValue(strategy = GenerationType.IDENTITY)

您需要做的是当您知道主键值即id值时,首先使用 findById() 方法从数据库中获取实体,通过该方法实体进入托管状态,然后尝试通过调用 save() 更新实体方法。 这将更新您的实体。

有关实体状态的更多信息,您可以参考: https : //vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-transitions/

要通过 JPA 更新现有实体对象,它应该首先可供实体管理器使用。

通读文章

https://www.objectdb.com/java/jpa/query/jpql/update

摘自同

1.Retrieving the entity objects into an EntityManager.
2.Updating the relevant entity object fields within an active transaction.
3.Applying changes to the database by calling the commit method.

我假设对于没有发生更新的情况,该实体还不是托管实体。

更多关于托管实体: https : //www.baeldung.com/hibernate-entity-lifecycle#managed-entity

这个问题已经得到回答,但这是我对主题的理解,因为我最近开始研究它。

这可以基于瞬态和持久/托管实体来回答。

瞬态实体:一个新创建的实体对象,迄今为止与任何会话都没有关联。 此对象与数据库中存储的任何数据无关,因为它是新创建的。

当您从 db 获取记录时,它以托管或持久状态获取,对它所做的任何更改都将反映回它所映射到的记录。

建议 1:您不应该手动添加主键值,因为它已经是 AutoIncremented。

建议2:如果您已经有recirds id,请先从db 中获取它,然后再更新它。

这是有关该主题的 Stackoverflow 讨论,可以让您获得更多见解: hibernate 中的分离、持久和瞬态对象是什么?

暂无
暂无

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

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