I have a composite key which houses 3 keys.
Composite key =>
@Embeddable
public class CompositeId implements Serializable{
@Column(unique = true)
private int deliveryId;
@MapsId
@OneToOne
@JoinColumn(name = "invoiceId",unique = true)
private Invoice invoiceId;
@MapsId
@ManyToOne
@JoinColumn(name = "customerId",nullable = false)
private Customer customerId;
}
Delivery Class=>
@Entity
public class Delivery {
@EmbeddedId
private CompositeId compositeId;
}
That's how the composite ID is used. deliveryId is for delivery entity itself and other keys are for shared primary keys.
When I write a session.createQuery
Query query = session.createQuery("from Delivery where compositeId.deliveryId=?");
query.setParameter(0,1);
and when it runs, it throws an exception:
javax.persistence.PersistenceException: org.hibernate.HibernateException: More than one row with the given identifier was found: 1, for class: example.test.Delivery
So I though of overriding equals and hashcode methods
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof Invoice) {
Invoice invoice = (Invoice) obj;
if (invoice.getInvoiceId() == this.invoiceId.getInvoiceId()) {
return true;
}
if (invoice.getDeliveryId() == this.invoiceId.getDeliveryId()) {
return true;
}
}
if (obj instanceof Customer) {
Customer customer = (Customer) obj;
if (customer.getCustomerId() == this.customerId.getCustomerId()) {
return true;
}
if (customer.getDeliveryId() == this.customerId.getDeliveryId()) {
return true;
}
}
return false;
}
but still I get the same error. And I thought It will fix it. But it didn't. I found the reason by following SQL and the reason is this gets 2 Customer and Item objects because of bidirectional relations. So how can I solve it?
Thanks :)