@OneToMany Relationship in Spring

A one-to-many association between the entities in JPA can be achieved using either of the  @ManyToOne or a @OneToMany annotations in Spring Boot.

According to Vlad Mihalcea,  @ManyToOne annotation allows you to map the Foreign Key column in the child entity mapping so that the child has an entity object reference to its parent entity, which is the most natural way of mapping one-to-many association.

Implementing a one-to-many association between the entities is a little tricky in Spring projects if extra care is not been taken into.

In JPA, a one-to-many association can either be unidirectional or bidirectional. The former choice is said to be inefficient as elucidated by Vlad.

Bi-directional @OneToMany Relationship in Spring Boot

Here in this, I am going to show an example of a one-to-many association between room and room amenities entities in a hotel universe.

Say, Room X in Hotel Taj in Mumbai. Room X would have many associated amenities such as free WiFi, a kitchen, etc.

Room Entity

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
public class Room {
    @Id
    @GeneratedValue(strategy = IDENTITY)
    private Long id;

    private String roomNumber;

    private BigDecimal rate;

    private int floorNumber;

    private int guestNumber;

    private Long bedCount;

    @OneToMany(
            mappedBy = "room",
            cascade = CascadeType.ALL,
            orphanRemoval = true
    )
    private List<RoomAmenity> roomAmenity = new ArrayList<>();
}
Code language: Java (java)

Room Amenities Entity

@NoArgsConstructor
@AllArgsConstructor
@Data
@Entity
public class RoomAmenity {
    @Id
    @GeneratedValue(strategy = <em>IDENTITY</em>)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "room_index")
    private Room room;

    private String roomAmenity;
}
Code language: Java (java)

Note

If you happen to miss adding @JoinColumn(name = "room_index"), another table will be created in your database containing foreign keys mapping to both room and room_amenity tables. Creating this additional table would make transactions to these tables very inefficient.

1 thought on “@OneToMany Relationship in Spring”

  1. Hi,

    This is one of the simplest example of relationships among entities in spring. Very good and simple explanation.

    Keep writing such simple articles explaining fundamental concepts.

    Regards
    Akhilesh Maurya

Leave a Reply

Discover more from BHUTAN IO

Subscribe now to keep reading and get access to the full archive.

Continue reading

Scroll to Top