Hibernate @ManyToOne

We can create a Many to One relationship between Persistent classes using @ManyToOne annotation.

Let us create a persistent class Planet and Galaxy as shown below. A set of Planets can belong to One galaxy. This creates a Many to One relationship. We can represent the same as shown below.

@Entity
@Table(name="COSMIC_GALAXY")
class Galaxy
{
    @Id
    @Column(name="galaxy_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name="galaxy_name")
    private String name;

    @OneToMany(mappedBy="galaxy")
    private Set<Planet> planets;
}

@Entity
@Table(name="COSMIC_PLANET")
class Planet
{
    @Id
    @Column(name="planet_id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Long id;

    @Column(name="planet_name")
    private String name;

    @ManyToOne
    @JoinColumn(name="galaxy_id")
    private Galaxy galaxy;
}

Previous: @OneToMany | Next: @ManyToMany - Unidirectional

<
>