code_junkie

How to map many-to-many List in Hibernate with a Link Table

Nov 13th, 2011
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. public class Parent{
  2.  
  3. private List<Child> _children;
  4.  
  5. //...getters and setters
  6. }
  7.  
  8. <class name="Parent">
  9. ....
  10. <list name="children" table="link_table">
  11. <key column="parent_id"/>
  12. <many-to-many column="child_id"
  13. class="Children"/>
  14. </list>
  15. ...
  16. </class>
  17.  
  18. <class name="Child">
  19. ...
  20. <list name="parents" inverse="true" table="link_table">
  21. <key column="child_id"/>
  22. <many-to-many column="parent_id"
  23. class="Parent"/>
  24. </list>
  25. ...
  26. </class>
  27.  
  28. @Entity
  29. public class Employer implements Serializable {
  30. @ManyToMany(
  31. targetEntity=org.hibernate.test.metadata.manytomany.Employee.class,
  32. cascade={CascadeType.PERSIST, CascadeType.MERGE}
  33. )
  34. @JoinTable(
  35. name="EMPLOYER_EMPLOYEE",
  36. joinColumns=@JoinColumn(name="EMPER_ID"),
  37. inverseJoinColumns=@JoinColumn(name="EMPEE_ID")
  38. )
  39. public Collection getEmployees() {
  40. return employees;
  41. }
  42. }
  43.  
  44.  
  45. @Entity
  46. public class Employee implements Serializable {
  47. @ManyToMany(
  48. cascade = {CascadeType.PERSIST, CascadeType.MERGE},
  49. mappedBy = "employees",
  50. targetEntity = Employer.class
  51. )
  52. public Collection getEmployers() {
  53. return employers;
  54. }
  55. }
Add Comment
Please, Sign In to add comment