我有一个客户对象,在该客户对象内我有一个包含用户名和密码的登录对象。当我执行 POST 请求时,请求工作正常,但是当我尝试执行 PUT 请求时,请求失败。它失败了,因为它说用户名上的条目重复。
我希望能够更新客户详细信息,而无需更改用户名。我怎样才能做到这一点。
这是我的代码:
用户登录实体:
@Entity
@Table(name = "Customer",
uniqueConstraints =
{
@UniqueConstraint(columnNames = "email"),
@UniqueConstraint(columnNames = "id"),
@UniqueConstraint(columnNames = "phoneNumber")
}
)
public class Customer implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int customerNumber;
@OneToOne(cascade= CascadeType.ALL)
@JoinColumn(name = "loginCredentialsID")
private UserLogin userlogin;
private String phoneNumber;
private String email;
private String physicalAddress;
private String country;
... getters and setters
}
用户登录实体:
@Entity
@Table(name = "UserLogin",
uniqueConstraints =
{
@UniqueConstraint(columnNames = "userName")
})
public class UserLogin implements Serializable, UserDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int loginCredentialsID;
private String username;
private String password;
... getters and setters
}
客户服务类:
public Response updatCustomeretails(int id,Customer customer) {
customer.setCustomerNumber(id);
if( customer== null ){
throw new ResourceNotFoundException("Empty", "Missing Data");
}else {
customerRepository.save(customer);
return new Response(" Customer Updated Successfully","Thank you ");
}
最佳答案
当使用 Sping data JPA 更新时,您应该使用您在保存此行 customerRepository.save(customer);
时正确执行的 save。但是,当在 PUT 请求中将数据持久保存到数据库时,JPA 使用实体映射中的键来更新正确的记录。
因此,在您的情况下,当 JPA 尝试保存新记录而不是对现有记录的更新时,您会收到该错误。您的意图是更新,但我怀疑您的 key 丢失或未正确定义,因此 JPA 尝试保存新记录而不是更新。
因此,当您执行更新(PUT)时,请确保您传递的对象与您要更新的对象具有相同的键。
关于java - 更新嵌套 Json 对象时 Springboot PUT 请求失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48933029/