【问题标题】:OneToOne JPA issueOneToOne JPA 问题
【发布时间】:2021-09-07 13:55:04
【问题描述】:

我有两节课

public class User {
     @Id
     @Column(name = "id")
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private Long id;
     private String name;
     private String age;
     @OneToOne
     @JoinColumn(name = "address_id", referencedColumnName = "id")
     private Address address;
}

public class Address {
     @Id
     @Column(name = "id")
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private Long id;
     private String building;
     private String country;
     @OneToOne(mappedBy = "address")
     private User user;
}

在我的表格地址中,我有几行。
当我用数据插入表用户时

{
   "id":null,
   "name":"Foo",
   "age":"18",
   "address":{
      "id":1,
      "building":"Too",
      "country":"ABS"
   }
}

表用户有 1 行 address_id =1。
我插入与上面相同的数据
表用户有 2 行 address_id =1。
我的回答是:为什么一对一连接的2个表会出现上述情况?

【问题讨论】:

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


    【解决方案1】:

    您可以在这里找到答案 Why @OneToOne is allowing duplicate associations?

    基本上,@JoinColumn(name = "address_id", referencedColumnName = "id") 本身并不能满足数据库中one-to-one 的语义,您需要将unique=true 添加到@JoinColumn 中,从而使其成为@JoinColumn(name = "address_id", referencedColumnName = "id", unique = true)

    旁注:我建议您删除表格,然后在尝试之前重新创建它们。如果你使用的是Hibernate,你可以将hibernate.hbm2ddl.auto设置为create-drop

    【讨论】:

      猜你喜欢
      • 2013-10-13
      • 1970-01-01
      • 2014-11-09
      • 2013-08-20
      • 1970-01-01
      • 2022-12-17
      • 1970-01-01
      • 2011-04-17
      • 1970-01-01
      相关资源
      最近更新 更多