I've got entity FooDetails, which has two fields: Customer and list of Location. Customer has Address (@OneToOne unidirectional mapping), and Location also has Address with @OneToOne mapping.
It happens that Address in Customer and in Location are the same. All these objects come from remote service and I manually put ID from remote object into entity before saving it. Mapping looks like this:
@Entity
@Table(name = "FOO")
public class FooDetails {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private long id;
@OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinColumn(name = "customer_id")
private Customer customer;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "details_id")
private Set<Location> locationList;
...
}
@Entity
@Table(name = "CUSTOMER")
public class Customer {
@Id
@Column(name = "customer_id", unique = true)
private long customerId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id")
private Address address;
...
}
@Entity
@Table(name = "LOCATION")
public class Location {
@Id
@Column(name = "location_id", unique = true)
private long locationId;
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "address_id")
private Address address;
...
}
@Entity
@Table(name = "ADDRESS")
public class Address{
@Id
@Column(name = "address_id")
private long addressId;
...
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StawareAddress)) return false;
StawareAddress that = (StawareAddress) o;
return addressId == that.addressId;
}
@Override
public int hashCode() {
return (int) (addressId ^ (addressId >>> 32));
}
}
When I receive whole FooDetails object from webservice I try to save it to local database.
If database is clean (no Addresses saved yet), one Address with proper id from WS is saved. If there already is an address with this id Hibernate tries to insert new one into database and it there is an error because of unique constraint on addressId.
I'm using Spring Data Jpa for saving entities (save() method).
What obvious entity mapping problem I missed?