java - Spring Data JPA duplicate entires -


i have customer table , address table in mysql. structure follows:

customer:{customer_id, name, email, shipping_address_id, mailing_address_id} address:{address_id, street_name, suburb, state, postcode} 

shipping_address_id, mailing_address_id foreign keys in customer table reference address_id in address table.

shipping_address_id, mailing_address_id have @onetoone uni-directional relation address_id.

@onetoone(cascade=cascadetype.all) @joincolumn(name = "shipping_address_id") private address shippingaddress;  @onetoone(cascade=cascadetype.all) @joincolumn(name = "billing_address_id") private address billingaddress; 

i have managed write rest endpoint can insert data these tables following payload:

{     "name": "testname",     "email": "test@test.com",     "shippingaddress": {         "streetaddress": "strert1",         "suburb": "testsuburb",         "state": "teststate",         "postcode": "testpostcode"     },      "mailingaddress": {         "streetaddress": "strert1",         "suburb": "testsuburb",         "state": "teststate",         "postcode": "testpostcode"     } } 

the problem when shipping_address , mailing address same, inserts address twice. there way check first before inserting record in address?. if address exists, possible link existing address customer?

happy provide code mapping if needed. have not defined specifications on crudrepository.save method

edit: implemented per suggestion m.aibin

controller

@requestmapping(value = "/customer", method = post) public responseentity<string> addcustomer(@requestbody customer customer) {     try {          customerservice.createcustomer(customer);     }     catch (exception ex) {         return new responseentity<>("error creating user: " + ex.tostring(), internal_server_error);     }     return new responseentity<>("user succesfully created! (id = " + customer.getcustomerid() + ")", ok); } 

service

public void createcustomer(customer customer) {     if(customer.getbillingaddress().equals(customer.getshippingaddress())){         customer.setshippingaddress(null);         customer savedcustomer = customerrepository.save(customer);         customer.setshippingaddress(savedcustomer.getbillingaddress());         customerrepository.save(customer);     }     else {         customerrepository.save(customer);     } } 

it works :) . wondering if there specification based method implement can similar to?

customerrepository.save(modifiedsave(customer)) 

if there no restriction columns not null, can following:

  1. check if addresses same

  2. if are, save customer object without mailing address object (this method can example return address object). set address object customer mailing id , update customer object in db.

  3. if values not same, 1 save.

hope understand way of thinking ;)


Comments