hibernatejpajpa-2.1

JPA - How can an entity refer to two other entities involved in a ManyToMany relationship?


I have the following tables:

enter image description here

In my domain model, I have a Car entity:

@Entity
@Data
public class Car {

    @Id
    private Long id;

    @ManyToMany
    @JoinTable(name="CarClassType",
        joinColumns= @JoinColumn(name="carId"),
        inverseJoinColumns = @JoinColumn(name="classTypeId"))
    private List<CarType> carTypes;
    
    private String model;
}

I also have a CarClassTypeSale and ClassType entities. I don't have a CarClassType entity. How should CarClassTypeSale class refer back to a Car and ClassType?

@Entity
@Data
public class CarClassTypeSale {

    @Id
    private Long id;

    @ManyToOne // this doesn't work; errors with invalid column name
    private Car car;

    @ManyToOne // this doesn't work; errors with invalid column name
    private ClassType classType;

}

Solution

  • The modelling here does not require a @ManyToMany as you can model the CarClassType as entity. Since the CarClassType table has an additional column id, you also actually can't model it this way. If you want this, you would have to use the two FKs also as primary key and drop the id column, which I would recommend you do anyway.

    @Entity
    @Data
    public class Car {
    
        @Id
        private Long id;
    
        @OneToMany(mappedBy = "car")
        private Set<CarClassType> carTypes;
        
        private String model;
    }
    @Entity
    @Data
    public class CarClassType {
    
        @EmbeddedId
        private CarClassTypeId id;
    
        @ManyToOne(fetch = LAZY)
        @JoinColumn(name = "carId", insertable = false, updatable = false)
        private Car car;
        
        @ManyToOne(fetch = LAZY)
        @JoinColumn(name = "classTypeId", insertable = false, updatable = false)
        private CarType classType;
    
        @OneToMany(mappedBy = "carClassType")
        private Set<CarClassTypeSale> sales = new HashSet<>();
    }
    @Embeddable
    @Data
    public class CarClassTypeId {
    
        @Column(name = "carId")
        private Integer carId;
        
        @Column(name = "classTypeId")
        private Integer classTypeId;
    }
    @Entity
    @Data
    public class CarClassTypeSale {
    
        @Id
        private Long id;
    
        @ManyToOne
        private CarClassType carClassType;
    
        private LocalDate soldDate;
    
    
    }
    

    Not sure how CarClassTypeSale fits into this picture. Your diagram does not really tell me how the class relates to the others.