Search code examples
javahibernatejpahibernate-mappinghibernate-annotations

Hibernate Mapping - How to Join Three Tables


I have 3 Entity: PERSON, CAR, and PROFFESION.

    @Entity
    @Table(name = "PERSON")
    public class Person implements Serializable {

        @Id
        private Long id;

        @OneToMany(mappedBy = "person", fetch = FetchType.EAGER)
        private List<Car> cars;

        @OneToMany(mappedBy = "person", fetch = FetchType.EAGER)
        private List<Profession> professions;
    }
    @Entity
    @Table(name = "PROFESSION")
    public class Profession implements Serializable {

        @Id
        private Long id;

        @ManyToOne
        @JoinColumn(name = "PERSON_ID")
        private Person person;
    }
    @Entity
    @Table(name = "CAR")
    public class Car implements Serializable {

        @Id
        private Long id;

        @ManyToOne
        @JoinColumn(name = "PERSON_ID")
        private Person person;
    }

When i'm trying to retrieve a person with connections to two professions and one car the result is two professions and two duplicated cars.

Or if he is connected to five cars and one profession, the result is five cars and five duplicated professions.

How should I correct the mappings so I receive the right results?


Solution

  • Use a Set to map oneToMany If you don't want duplicates. Its mapped with the <set> element in mapping table. so first you make changes to these parts:

    private Set<Car> car = new HashSet<Car>(0);
    
    @OneToMany(fetch=FetchType.LAZY, mappedBy="persons")
        public Set<Car> getCar() {
            return this.car;
     }
    public void setCar(Set<Car> car) {
            this.car = car;
        }
    

    Do the same with profession and another oneToMany you do not want duplicates. you can set fetchType based on loading preferences. Eager load all at once and Lazy load on demand which is usually best.