Friday, May 16, 2014

Hibernate relationship templates

Here is a list with one-to-many, one-to-one and many-to-many relations templates.

One-to-many:
@Entity(name = "parent")
@Access(AccessType.FIELD)
public class Parent {

    @OneToMany(fetch = FetchType.LAZY, mappedBy="childVarName", orphanRemoval=true)
    protected Set<Child> parentVarName;
}

@Entity(name = "child")
@Access(AccessType.FIELD)
public class Child {
    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "child", nullable = false)
    protected Parent childVarName;
}

One-to-one:
public class VirtualParent {
    @OneToOne(mappedBy = "virtualParentVar")
    protected VirtualChild virtualChildVar;
    // ...
}

public class VirtualChild {
    @OneToOne
    @JoinColumn(name = "frn_virtual_parent_id")
    protected VirtualParent virtualParentVar;
    // ...
}

Many-to-many:

No comments:

Post a Comment