November 21, 2024

How to Set Unique Column As forgeinKey In Jpa Mapping

Hi when I try to save customer details with email as foreign key the email column remains null in the address table. I have tried moving joinColum to customer class as well but then it stores Integer Id as the foregin key

@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;

   }

address class

@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 Request

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