In my web application I use several different JPA queries to retrieve objects from database and populate my http session data structure. This includes list of cars, list of groups of cars and some other structures containing cars.
Any car can be included in several different structures. For example the same car can be included in group G (as the first car in this group) and be the property of Driver D. So that D.getCar() and G.getCars().get(0) refer to the same database entity (correspond to the same database row). But not the same object instance. That's because I'm retrieving groups of cars and drivers in separate queries. But I want the same database entitites in my structure be the same objects. So that for example I will be able to change transient data of D.getCar() and the changes will be reflected in G.getCars().get(0).
Is there any way to implement this transparently using JPA? I perform only reading operations on database, so I don't care about whether the entitites in my structure are managed or not. I'm changing only transient data.
Of course the possible solution is to manually traverse through my objects structure looking for Car instances with the same id property and replacing duplicates with the same object instance but this is really a headache.
Any query to the same EntityManager (if JEE also must be in same JTA transaction), will maintain object identity and return the same object for the same row.
You seem to be executing each query in a different EntityManager, (or different JTA transaction), so if you want to have object identity preserved, you need to use the same EntityManager for the entire request.
Actually I'm using spring for my JPA transactions. So I've put @Transactional annotation on the method which performs queries and YES, it works! No object duplication for the same database entity.