문제

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.

@Entity
public class Trip {

 @OneToOne
 private Location fromLocation;

 @OneToOne
 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

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

and will need the same treatment.

Any ideas please? Thanks!

도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top