Everytime I use the method save of a JPA Spring data repository it give me back a new object and the Autogenerated PK are not updated in the saved object.
Do I have to update my local object PK with the returned by save method manually?
Code:
private void saveProject(){
Project savedProject = projectRepository.save(projectModel.getProject());
}
savedProject is not the same as projectModel.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;
[...]
}
And:
@Entity
@Table(name = "user", schema = "public")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Integer id;
String name;
}
So, the user PK is gerenated in Mysql, and everytime I save the project a new User is created because the user in the app is still PKless...
答案 0 :(得分:1)
每次保存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.