Hibernate/JPA one-to-many relationship if parent reference is defined as an ID with no parent reference

StackOverflow https://stackoverflow.com/questions/21944946

Question

Standard way to define one-to-many relationship in Hibernate/JPA is to have a reference in a Child object to its Parent object.

@Entity
@Table(name="PARENT")
public class Parent {
    // ...

    @OneToMany(mappedBy="department")
    private Set<Child> children;

    // ... 
}



@Entity
@Table(name="CHILD")
public class Child {
    // ...

    @ManyToOne
    @JoinColumn(name="parent_id")
    private Parent parent;

    // ... 
}

The problem with this method is that Child becomes a heavyweight class, which is harder to send across the wire, etc.

Is it possible to define a one-to-many relationship with no Parent object referenced from Child and with no additional reference/join table? In that case Child class defined as follows:

@Entity
@Table(name="CHILD")
public class Child {
    // ...

    @Column(name="DEPARTMENT_ID")
    private Long departmentId;

    // ... 
}

No correct solution

OTHER TIPS

If you are using JPA 2.0, it is possible OneToMany uni-direction with no parent entity at child entity.

Parent.java

@Entity
@Table(name="PARENT")
public class Parent {
    @OneToMany
    @JoinColumn(name = "PARENT_ID", referencedColumnName = "ID")
    private Set<Child> children;
}

Child.java

@Entity
@Table(name="CHILD")
public class Child {
    // No need to hold parent entity
    //@ManyToOne
    //@JoinColumn(name="parent_id")
    //private Parent parent;
}

More Reference

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top