I have a problem that loading my lazy collections produces a lot of SQL-Statements and I wonder if there is no more efficient way of loading the data.
Situation:
Parent has a lazy collection of Child called children. It is actually a Many-To-Many relation.
I load a list of Parents with a CrudRepository and I need to get all child_ids for each Parent. So every time I access the children collection i executes a new SQL-Statement.
If i load 200 Parents there are 201 queries executes (1 for the list of Parents and 1 for each Parent's children).
Any idea how i can load the data with just one query?
EDIT 1
Parent/Child is probably a bad naming here. In fact i have a Many-To-Many relation.
Here is some code:
@Entity
public class Tour {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",
strategy = "uuid2")
@Column(length = 60)
private String id;
@ManyToMany
@JoinTable(
name="parent_images",
joinColumns = @JoinColumn(name="tour_id", referencedColumnName = "id"),
inverseJoinColumns = @JoinColumn(name="image_id", referencedColumnName = "id"),
foreignKey = @ForeignKey(name = "FK_TOUR_IMAGE_TOUR"),
inverseForeignKey = @ForeignKey(name = "FK_TOUR_IMAGE_IMAGE")
)
private List<Image> images = new ArrayList<>();
}
@Entity
public class Image {
@Id
@GeneratedValue(generator = "system-uuid")
@GenericGenerator(name="system-uuid",
strategy = "uuid2")
@Column(length = 40)
private String id;
//....
}
// Code to fetch:
@Autowired
TourRepository repo;
List<Tour> tours = repo.findBy(....);
List<String> imageIds = new ArrayList<>();
for(Tour tour : tours){
imageIds.addAll(tour.getImages().stream().map(b -> b.getId()).collect(Collectors.toList()));
}
JdbcTemplate, for example) for this method and write a simple sql likeselect parent_id, child_id from parents, childs join ...?