List seems to be working it doesnt fetch collections anymore on add using Parent method still fetches entities I'm not sure why. From what I know getReference shouldn't generate select unless I access property but it generates select without accessing anything.
Code:
@Entity(name = "Child")
public class Child implements Serializable{
@Id
@GeneratedValue
private Integer id;
@OneToMany(mappedBy = "child", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ParentChild> parents = new ArrayList<>();
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Child u = (Child)o;
return Objects.equals( id, u.id );
}
@Override
public int hashCode() {
return Objects.hash( id );
}
}
@Entity(name = "Parent")
public class Parent implements Serializable{
@Id
@GeneratedValue
private Integer id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.ALL, orphanRemoval = true)
private List<ParentChild> children = new ArrayList<>();
public void addChild(Child child){
ParentChild parentChild = new ParentChild(this,child);
this.children.add(parentChild);
child.getParents().add(parentChild);
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
Parent u = (Parent)o;
return Objects.equals( id, u.id );
}
@Override
public int hashCode() {
return Objects.hash( id );
}
}
@Entity(name = "ParentChild")
public class ParentChild implements Serializable{
@Id
@ManyToOne
private Parent parent;
@Id
@ManyToOne
private Child child;
public ParentChild(Parent parent, Child child) {
this.parent = parent;
this.child = child;
}
public ParentChild() {
}
@Override
public boolean equals(Object o) {
if ( this == o ) {
return true;
}
if ( o == null || getClass() != o.getClass() ) {
return false;
}
ParentChild that = (ParentChild) o;
return Objects.equals( parent, that.parent ) &&
Objects.equals( child, that.child );
}
@Override
public int hashCode() {
return Objects.hash( parent,child );
}
}
Code:
@Override
@Transactional
public void linkChildToParent(Integer childId, Integer parentId){
Parent parent = em.getReference(Parent.class,childId);
Child child = em.getReference(Child.class,parentId);
parent.addChild(child);
}