【问题标题】:How to Set Unique Column As forgeinKey In Jpa Mapping如何在 Jpa 映射中将唯一列设置为 forgeinKey
【发布时间】:2022-01-26 05:32:59
【问题描述】:

您好,当我尝试使用电子邮件作为外键保存客户详细信息时,地址表中的电子邮件列仍然为空。我也尝试将 joinColum 移动到客户类,但随后它将 Integer Id 存储为外键

@Entity
@Getter
@Setter
@NoArgsConstructor
public class Customer implements Serializable {
   @Id
   @GeneratedValue
   private Integer id;

   private String name;

   @Column(unique = true)
   private String email;

   @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER,mappedBy = "customer")
   private Set<Address> addresses;

   }

地址类别

@Entity
@NoArgsConstructor
@Getter
@Setter
public class Address implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer addressId;
    private String address;

    @ManyToOne
    @JoinColumn(referencedColumnName = "email")
    private Customer customer;
}

Json 请求

{   
    "name":"someName",
    "email":"someEmail",
    "addresses":[
        {
            "address":"exampleAddress1"
        },
        {
            "address":"exampleAddress2"
        }
    ]
}

【问题讨论】:

  • 请在您填充和使用这些对象的位置添加您的代码。
  • @PostMapping public ResponseEntity create(@RequestBody Customer customer) { Customer savedDetails = customerRepository.save(customer); return new ResponseEntity(savedDetails, HttpStatus.CREATED);实际上我正在尝试将 json 请求直接从控制器保存到存储库

标签: sql spring spring-boot jpa


【解决方案1】:

可以通过引用父列的主键或唯一键来创建外键约束。

实体可以使用子对象或父对象保存,因为它是双向关系。但是在保存之前链接这两个对象。

请根据您的用例选择方法。

使用地址实体保存

Customer customer = Customer.builder().email("abc").name("name")
                .build();
        Set<Address> addressSet=new HashSet<>();
        Address a1 = Address.builder().address("addressname").customer(customer).build();
        addressRepository.save(a1);

使用客户对象保存

    Set<Address> addressSet = new HashSet<>();
        Customer customer = Customer.builder().email("abc").name("name")
                .build();
        Address a1 = Address.builder().address("addressname").customer(customer).build();
        addressSet.add(a1);
        customer.setAddresses(addressSet);
        entityRepository.save(customer);

为避免该问题对象引用了未保存的瞬态实例 - 在刷新之前保存瞬态实例请相应地添加级联类型。

 @ManyToOne(fetch = FetchType.LAZY,cascade=CascadeType.ALL)
    @JoinColumn(name = "customer_email",referencedColumnName = "email")
    private Customer customer;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-21
    • 2019-07-02
    • 2012-05-14
    • 2014-11-02
    • 2020-07-22
    • 2021-07-11
    • 2021-07-26
    • 1970-01-01
    相关资源
    最近更新 更多