Created
February 26, 2016 16:11
-
-
Save heruan/9cbe7ae13f94d4fc2d2c to your computer and use it in GitHub Desktop.
Entity with multiple reference to a composite-id foreign key throws EntityExistsException
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
public class Company { | |
@Id | |
public Long id; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Entity | |
@IdClass(Customer.class) | |
public class Customer { | |
@Id | |
public Long id; | |
@Id | |
@ManyToOne | |
public Company company; | |
public Customer related; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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