Home > Software engineering >  How to Set Unique Column As forgeinKey In Jpa Mapping
How to Set Unique Column As forgeinKey In Jpa Mapping

Time:12-30

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"
        }
    ]
}

CodePudding user response:

A foreign key constraint can be created by referring to either primary key or unique key of the parent column.

The entities can be saved either using child object or a parent object since its a bidirectional relationship. However link both the objects before saving.

Please choose the approaches according to your use case.

Saving using Address entity

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

Saving using Customer Object

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

To avoid the issue object references an unsaved transient instance - save the transient instance before flushing please add the cascadetype accordingly.

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