【问题标题】:Duplicate entry when using one to one relationship with shared primary key in JPA在 JPA 中使用与共享主键的一对一关系时出现重复条目
【发布时间】:2022-07-15 16:37:42
【问题描述】:

我按照下面的使用共享主键建模的例子:

@Entity
@Table(name = "users")
public class User {

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

    //...

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL)
    @PrimaryKeyJoinColumn
    private Address address;

    //... getters and setters
}

@Entity
@Table(name = "address")
public class Address {

    @Id
    @Column(name = "user_id")
    private Long id;

    //...

    @OneToOne
    @MapsId
    @JoinColumn(name = "user_id")
    private User user;
   
    //... getters and setters
}

但是,如果地址表中已经有 id 为 123456 的记录,那么我尝试如下更新记录:

Address po = new Address();
po.setId(123456L);
po.setCountry("TW");
AddressRepository.save(po);

将出现重复的条目“123456”键异常。为什么 JPA 会插入新记录而不是合并它?如何解决这个问题?

【问题讨论】:

    标签: java spring-boot jpa spring-data-jpa


    【解决方案1】:

    您必须使用findById 读取地址,而不是创建新实例。

    如果您创建一个新实例,它会尝试插入一条新记录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-26
      • 2011-05-16
      • 1970-01-01
      • 2020-03-09
      • 2015-07-13
      • 2018-05-19
      • 1970-01-01
      相关资源
      最近更新 更多