Skip to content

Instantly share code, notes, and snippets.

@heruan
Created February 26, 2016 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heruan/9cbe7ae13f94d4fc2d2c to your computer and use it in GitHub Desktop.
Save heruan/9cbe7ae13f94d4fc2d2c to your computer and use it in GitHub Desktop.
Entity with multiple reference to a composite-id foreign key throws EntityExistsException
@Entity
public class Company {
@Id
public Long id;
}
@Entity
@IdClass(Customer.class)
public class Customer {
@Id
public Long id;
@Id
@ManyToOne
public Company company;
public Customer related;
}
public class CustomerId {
public Long id;
public Long company;
@Override
public int hashCode() {
return (int) (this.id + this.company);
}
@Override
public boolean equals(Object object) {
if (object instanceof CustomerId) {
CustomerId customerId = (CustomerId) object;
return (this.id == customerId.id) && (this.company == customerId.company);
} else {
return false;
}
}
}
@Stateless
public class CustomerService {
@PersistenceContext
private EntityManager em;
public void createCustomer() {
Company company = new Company();
company.id = 1;
Customer customerOne = new Customer();
customerOne.id = 1;
customerOne.company = company;
Customer customerTwo = new Customer();
customerTwo.id = 2;
customerTwo.company = company;
customerTwo.related = customerOne;
this.em.merge(customerTwo);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment