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

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

问题描述

我正在尝试更新数据,并且据我所知,如果id为null,则save()方法将保存实体;如果在数据库中找到了给定的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()方法从数据库中获取实体,该实体进入托管状态,然后尝试更新实体通过调用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储存库save()不会更新现有数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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