JPA @ManyToOne Annotation

In this blog post, we will learn everything about JPA @ManyToOne annotation with an example.

JPA @ManyToOne Annotation Overview

The @ManyToOne annotation is used to define a many-to-one relationship between two entities in JPA. It indicates that multiple instances of the source entity (child) are related to a single instance of the target entity (parent). In essence, many children entities belong to one parent entity.

Here are the most commonly used attributes of the @ManyToOne annotation: 

targetEntity: 

Specifies the target entity class to which the relationship is mapped. It is required when the target entity is not directly inferred from the type of field. 

Example: @ManyToOne(targetEntity = Department.class)

fetch: 

Defines the fetching strategy for the association. It determines when the associated parent entity should be loaded from the database. Two common options are FetchType.LAZY (loads the parent entity on-demand when accessed) and FetchType.EAGER (loads the parent entity immediately with the child entity). 

Example: @ManyToOne(fetch = FetchType.LAZY) 

optional: 

Specifies whether the relationship is optional or required (not nullable). If set to false, the child entity must always be associated with a parent entity. By default, the optional attribute is true. 

Example: @ManyToOne(optional = false) 

cascade: 

Specifies the cascade operations that should be propagated from the parent entity to the child entity. Use the CascadeType enum to specify one or more cascade types:

  • CascadeType.ALL
  • CascadeType.PERSIST
  • CascadeType.MERGE
  • CascadeType.REFRESH
  • CascadeType.REMOVE

Example: @ManyToOne(cascade = CascadeType.ALL)

JPA @ManyToOne Annotation Example

The below ER diagram shows one Instructor can have many Course entities and many Course entities belong to one Instructor only.

The @OneToMany and @ManyToOne JPA annotations are used to link one-to-many bidirectional entity mapping.

Instructor JPA Entity

import java.util.List;

import jakarta.persistence.*;

@Entity
@Table(name = "instructor")
public class Instructor {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

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

    @OneToMany(mappedBy = "instructor", cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH,
      CascadeType.REFRESH })
    private List<Course> courses;

    // getter / setter methods
}

Course JPA Entity

import jakarta.persistence.*;

@Entity
@Table(name = "course")
public class Course {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int id;

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

    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "instructor_id")
    private Instructor instructor;

    // getter / setter methods
}

In this example, the Course entity has a field instructor annotated with @ManyToOne. The @JoinColumn annotation specifies the foreign key column (instructor_id) in the Course table that maintains the relationship with the Instructor table.

Cascading Operations

Similar to other JPA annotations, the @ManyToOne relationship supports cascading operations. If you apply cascade operations on the parent entity, those operations will cascade down to the child entities. 

For example, you can set the cascade attribute to CascadeType.ALL to propagate all operations from the Instructor to its associated Course entities. 

Fetching Strategies

The @ManyToOne relationship can have two fetching strategies: eager and lazy. 

By default, it uses the eager fetching strategy, which means that the associated Instructor entity will be loaded from the database immediately when the Course entity is fetched. To use lazy fetching, set the fetch attribute to FetchType.LAZY. 

Bidirectional Mapping

Bidirectional mapping is possible with the @ManyToOne relationship. To establish a bidirectional relationship, you can add a corresponding @OneToMany relationship in the Instructor entity, creating a two-way association between the Instructor and Course. 

Conclusion

In this blog post, we learned everything about JPA @ManyToOne annotation with an example.

The @ManyToOne annotation in JPA is a powerful tool for mapping many-to-one relationships between entities. By using this annotation, developers can create sophisticated data models that accurately represent the associations between entities.

Complete Many-to-One Mapping Examples

JPA Hibernate One to Many Unidirectional Mapping Example

References

Comments