Spring 数据保存不更新持久化上下文中的PK?

Spring data save does not update the PK in the persistence context?

每次我使用 JPA Spring 数据存储库的保存方法时,它都会返回一个新对象,并且自动生成的 PK 不会在保存的对象中更新。

我是否必须使用 save 方法返回的手动更新我的本地对象 PK?

代码:

private void saveProject(){
        Project savedProject = projectRepository.save(projectModel.getProject());
}

savedProjectprojectModel.getProject

不同
@Entity
@Table(name = "project", schema = "public")
public class Project {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Integer id;

    @LazyCollection(LazyCollectionOption.FALSE)
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    List<User> users;
    [...]
}

并且:

@Entity
@Table(name = "user", schema = "public")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    Integer id;

    String name;
}

因此,用户 PK 在 Mysql 中生成,每次我保存项目时都会创建一个新用户,因为应用程序中的用户仍然没有 PK...

每次保存 new Project(),JPA 都会在数据库中创建一个新对象。

要更新一个实体,您需要首先像这样从数据库中获取实体,从而将该实体放入 JPA 上下文中。

Project lastProject = projectRepository.findById(PROJECT_ID); //lastProject is now updatable.
lastProject.setName(...);   //update the entity fields
lastProject = projectRepository.save(lastProject); //project will now have the updated name.