首页 > 解决方案 > Spring boot/Spring data jpa - 如何更新相关实体?

问题描述

我有以下实体:

@Entity
@Table(name = "profile")
public class Profile {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @OneToOne(cascade = CascadeType.ALL)
    private ProfileContacts profileContacts;

...

}

@Entity
@Table(name = "profile_contacts")
public class ProfileContacts {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "description")
    private String description;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

}

我正在尝试通过将此带有更新的 JSON 发送到 REST 控制器来更新它:

{
        "id": 1,
        "description": "an update",
        "profileContacts": {
            "firstName": "John",
            "lastName": "Doe"
        }
 }

所以最后它调用

profileRepository.save(profile);

profileRepository类的实例在哪里ProfileRepository

public interface ProfileRepository extends JpaRepository<Profile, Long> {
}

这是spring-data-jpa界面。

但是每次更新后它都会更新profile表,但会向表(对应于实体的表)添加行,而不是更新现有行。如何实现更新?profile_contactsProfileContacts

标签: javahibernatespring-bootjpaspring-data-jpa

解决方案


根据您的 JSON 结构。profileContacts是的,它每次都会创建新条目。

每次保存profile您传递的实体时都会出现问题"id": 1,这意味着 Hibernate 可以通过该id值(主键)识别实体,但是对于profileContacts映射,您没有发送,id这就是 Hibernate 每次都考虑它有一个新实体的原因。

要更新您的profileContacts实体,请确保传递它的 id。

例子:

{ 
"id": 1,
 "description": "an update", 
"profileContacts": {
"id" : yourEntityId
 "firstName": "John", 
"lastName": "Doe" 
}
 }

推荐阅读