I have a table that hold a some relation that a commune to multiple other tables. Let’s call that Table Animal
Animal model
@Entity
public class Animal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// other things
@OneToOne(mappedBy = "animal" )
private Tiger tiger;
@OneToOne(mappedBy = "animal" )
private Fox fox;
}
I have Tiger and Fox and others that hold the foreign key animal_id
Tiger model
@Entity
public class Tiger {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
// other things
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "animal_id", referencedColumnName = "id", nullable = false)
private Animal animal;
}
Fox is quite similary to Tiger. Everythings works but When I try to retrieve Tiger or Fox, It create a lot of SQL request.
First 1 request to Get the List of Tiger and N times animal with left join Tiger and LEFT JOIN Fox. So If I have 15 Tiger in database (db), It will trigger 16 SQL request and if I have 150 Tiger in db, it’ll trigger 151 SQL request.
I did try to create a query in my repository, but doesn’t seems to work.
@Query("SELECT t From Tiger t LEFT JOIN t.animal a LEFT JOIN a.fox f")