I need some help with the following case please.

I have two tables Trips and Location. The Trip entity has two @OneToOne associations with the Location table.

This would be the entity.

public class Trip {

 private Location fromLocation;

 private Location toLocation;

The entity is currently hydrated by repository methods such as:

Trip findById(Long id);

Everything works correctly as it is but the problem is that for each trip it makes two calls to the Location table. Is there any way to reduce this to just one call without changes to the database structure?

I've already tried putting a native query with a join on the tables on the repository method but due to the @OneToOne annotation the calls still happen. Removing the annotation and populating Locations with alternate repository methods is not an option either since further down the road I have an entities which have

private List<Trip> trips = new ArrayList<>();

and will need the same treatment.

Any ideas please? Thanks!

Was it helpful?


As it stands at the moment, no.

This is because you have references to two separate objects, identified by two different PK's.

You would have to write a strange custom query to query for the 2 primary keys, return both objects, write logic to separate the fromLocation and the toLocation objects, then set each object to their respective object within the Trip. You'd probably be looking at more overhead doing this than letting Hibernate just run the 2 queries and give you back the entire Trip object.

If you are super-worried about performance, I'd suggest setting up a second-level cache for these objects. Trying to retrieve the two objects in one custom query, is just unnecessary complication of something that Hibernate does (relatively) efficiently enough on its own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top