Guest User

Untitled

a guest
May 21st, 2018
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. @Entity
  2. public class Parent {
  3. // ...
  4.  
  5. @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY, cascade = CascadeType.REMOVE)
  6. private Set<Child> children = new HashSet<Child>();
  7.  
  8. // ...
  9. }
  10.  
  11. @Entity
  12. public class Child {
  13. // ...
  14.  
  15. @ManyToOne(fetch = FetchType.LAZY)
  16. private Parent parent;
  17.  
  18. // ...
  19. }
  20.  
  21. Parent parent = new Parent();
  22. em.persist(parent);
  23.  
  24. // ...
  25.  
  26. Child child = new Child();
  27. child.setParent(parent);
  28. em.persist(child);
  29.  
  30. parent.getChildren().size(); // returns 0
  31.  
  32. public void addChild(Child child) {
  33. child.setParent0(this);
  34. getChildren().add(individualNeed);
  35. }
  36.  
  37. public void setParent(Parent parent) {
  38. parent.addChild(child);
  39. }
  40.  
  41. public void setParent0(Parent parent) {
  42. this.parent = parent;
  43. }
  44.  
  45. @Entity
  46. public class Parent {
  47. // ...
  48.  
  49. @OneToMany(mappedBy = "parent", fetch = FetchType.LAZY,
  50. cascade = {CascadeType.REMOVE, CascadeType.PERSIST})
  51. @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
  52. private Set<Child> children = new HashSet<Child>();
  53.  
  54. // ...
  55. }
  56.  
  57. @Entity
  58. public class Child {
  59. // ...
  60.  
  61. @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
  62. @Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
  63. private Parent parent;
  64.  
  65. // ...
  66. }
  67.  
  68. Parent parent = new Parent();
  69. em.persist(parent);
  70.  
  71. // ...
  72.  
  73. Child child = new Child();
  74. child.setParent(parent);
  75. em.persist(child); //will cascade update to parent
  76.  
  77. parent.getChildren().size(); // returns 1
  78.  
  79. Parent parent = new Parent();
  80. Child child = new Child();
  81. parent.setChild(parent);
  82. em.persist(parent); //will cascade update to child
  83.  
  84. child.getParent(); // returns the parent
Add Comment
Please, Sign In to add comment