mercredi 22 janvier 2020

How does Hibernate fetch data in a OneToMany relationship under the hood?

I am developing an ORM library similar to Hibernate. Now I'm stuck with the OneToMany relationship. I'd like to know how to fetch automatically data from database when getter of the one side is called and how Hibernate does it under the hood.

Many side

public class Film {
    private int id;
    private String name;

    @JoinColumn(name="producer_id")
    private Producer producer;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Producer getProducer() {
        return producer;
    }

    public void setProducer(Producer producer) {
        this.producer = producer;
    }
}

One Side

public class Producer {
    @Id
    private int id;
    private String name;

    @OneToMany(mappedBy="producer")
    private Set<Film> films;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setName(String name) {
        this.name = name;
    }

    // When called, it executes: SELECT ... FROM Film where producer_id = ?
    public Set<Film> getFilms() {
        return films;
    }
}

In other words, I want to fill films inside Producer only when getFilms() is called.





Aucun commentaire:

Enregistrer un commentaire