1

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

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
sajithneyo
  • 431
  • 2
  • 5
  • 16

1 Answers1

0

For your primary issue, the HibernateException, please switch on the hibernate.show_sql = true and see what is the SQL being fired and the results coming back.

The mapping however looks fine and works for with same structure and different class/table names.

For the second part, the equals method, I would suggest to use auto-generated method from Eclipse and include all the properties. Your Invoice and Customer class must also implement equals and hashCode methods. The implementation of equals here wil not be useful since hibernate will not pass instance of Invoice and Customer to compare with instance of CompositeId.