开发者

Entity relationships design with JPA2

I have two entities, User and UserSetting. The obvious relationship between these two has User as the first rate entity which contains a set / list of UserSettings so when a User is loaded the settings get loaded too. E.g User 1-->* UserSetting

Trouble is that's not what I want. At the moment users only have a few settings but that won't always be the case and when a user is active in the system they typically only need access to a small subset of all their settings. What I want is to load individual user settings on demand. The obvious choice is to make the UserSetting list lazy load but that won't work as I want to use the User in a detached state.

My curren开发者_如何学Got "solution" is to include the User in the UserSetting object but that feels wrong as it makes the relationship UserSetting *-->1 User which feels like the UserSetting is the dominant entity. Is this the best solution?

Assuming my current solution is the best I can get will a delete of the User still cascade correctly?


There's 2 points here

  1. First, if your User entity has an association towards UserSettings and that association can contain a lot of members which are not needed all the time, the right thing to do is configure it as lazyLoaded by default (via JPA2 mapping config) and then force an eager fetch on it only when you need to (i.e. in those situations you mentioned where you need the values of that assocation on a detached User Entity). Look at "join fetch" to see how to do this, it should be something like:

    SELECT u FROM User u JOIN FETCH u.userSettings

  2. If there's only a subset of those UserSettings that are needed often, you could make two associations in the User entity, such as userSettingsMain and userSettingsExtra, both lazy loaded by default, and just join fetch the one you needed on a certain detached User entity. Or, as a more advanced thing, you can make a Map association on the user settings, and have different keys for the important UserSetting, and the extra ones (such as i1, i2,... e1, e2, etc) and then eagerly fetch only those sets of keys that are needed, but this only works (at least at the moment) with EclipseLink JPA2, Hibernate's implementation just throws a big exception on Map associations (see my question here: Hibernate JPQL - querying for KEY() in Map association error on this)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜