Search code examples
hibernatehibernate-mapping

Hibernate ORM mapping between Java classes


I have two Java classes Match (a Cricket match) and ball. In a match, there will be many balls and every ball will be part of a match. I need hibernate mapping between these two classes in a way,

  1. if I call save on match object, it should be able to persist all containing balls in ball table and remaining match details in match table.

  2. If I call save or update on ball object, first it should go to match table to check if match id present in ball object is available there or not. If it is there, it should save or update the ball object in ball table.

If any one does not know Match-Ball relation in Cricket, he can think as Foot Ball Match - Goal relation. In a match there can be n number of Goals and every goal will be part of a match. Saving Match should also be able to save all the contained goals in goal table and saving goal object should check in match table with its id and then should save goal details in goal table.

Thanks.


Solution

  • I think it is @ManyToOne and @OneToMany annotations will work for you. If you will save object Match which will (must) contain list of Goals, every Goal will save with Match.

    Match.java

    import javax.persistence.*;
    import java.util.List;
    
    @Entity
    @Table(name = "match")
    public class Match {
    
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        protected Integer id;
    
      @JsonBackReference
      @OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
      @JoinTable(name = "goal", joinColumns = {
            @JoinColumn(name = "match_id", nullable = false, updatable = false) },
            inverseJoinColumns = { @JoinColumn(name = "goal_id",
                    nullable = false, updatable = false) })
        protected List<Goal> goals;
    }
    

    Goal.java

    import javax.persistence.*;
    import java.util.List;
    
    @Entity
    @Table(name = "goal")
    public class Goal {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        protected Integer id;
    
        @JsonBackReference
        @ManyToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
        @JoinTable(name = "match", joinColumns = {
            @JoinColumn(name = "goal_id", nullable = false, updatable = false) },
            inverseJoinColumns = { @JoinColumn(name = "match_id",
                    nullable = false, updatable = false) })
        protected Match matche;
    
    }