Jpa Repository save() 不更新现有数据 [英] Jpa Repository save() doesn't update existing data

查看:231
本文介绍了Jpa Repository save() 不更新现有数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to update data and as I know save() method saves entity if the id is null or update an existing entity in the database if the given id is found in DB.

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

However, when I try to save data it is not updated:

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

    return repository.save(emp);
}

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

But, when I retrieve data from the database and update its fields and save again it updates:

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

    return repository.save(emp);
}

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

Can anyone explain the reason for this behavior? I read the documentation but couldn't find anything related to that.

这是我的存储库:

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).

Your Entity Employer looks to be in detached/Transient state and you are passing id value manually which is not permitted, as it is marked as @GeneratedValue(strategy = GenerationType.IDENTITY).

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

What you need to do is when you know the primary key value i.e id value, first you fetch the Entity from the database using findById() method, by which Entity comes into Managed state and then try to update the Entity by calling save() method. This will update your Entity.

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

For more info on Entity state you can refer this: https://vladmihalcea.com/a-beginners-guide-to-jpa-hibernate-entity-state-transitions/

这篇关于Jpa Repository save() 不更新现有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆