If a data model includes one-to-one relationships that are optional/nullable, what's the best way to represent those so that the second-level cache will do the right thing?
For example, a Car may have zero or one Stereo, but a Stereo will always belong to a Car:
Code:
@Entity
public class Car {
...
@OneToOne(optional = true)
@PrimaryKeyJoinColumn
private Stereo stereo;
...
}
@Entity
public class Stereo {
...
@OneToOne(optional = false, mappedBy = "stereo")
@PrimaryKeyJoinColumn
private Car car;
...
}
I've tried a lot of variations on this, and I've found that the second level cache (EHCache) handles this association right when the owner (Car) and the owned (Stereo) both exist. If the Car has no Stereo, however, I see a query for the missing Stereo every time I pull it out of the cache. I.e. it doesn't seem like the cache can store a null to say "this Car has no Stereo, so don't bother asking about it ..."
The caching works right for one-to-one relationships where optional=false.
The only way I've found to get the right behavior for this case is to model the relationship as a one-to-many where my business logic just maintains it as a one-to-one. When I do this, I can set up the cache for the entities and the collection, and I don't see extra queries for the missing child. This works ok, but feels like a hack. Is there a cleaner way to model this?[/code]