proper modelling and persistence

View: New views
2 Messages — Rating Filter:   Alert me  

proper modelling and persistence

by measwel :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Hallo,

I have a question regarding proper modelling and persistance using JPA. I have a user entity and a favorite entity. The user has a collection of favorites. A new favorite is created. I have two options:

1) I call the jpa controller of favorite and persist a new favorite to the DB. When a user wants to see his favorites, I read them via the favorite JPA controller from the DB, filtering on the user.

2) I add the new favorite to the collection of favorites for that user. If the user wants to see his favorites, I read them from the collection of favorites that he has.

What is the correct way to model the above situation? If I use option 2, then how can I persist the new collection to the DB?

Thank you,
measwel

Re: proper modelling and persistence

by James Sutherland :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Your questions seems to be whether to define a OneToMany or query for the relationship.

Normally in an object oriented system, I would say it is better to model the OneToMany in the model.  So, User has a Collection favorites to Favorite.  Make sure when you create a new Favorite you both add it to the User's favorites Collection and set its user.

However, it depends on how big the Collection is, and how it will be used.  If a User can have 100-1,000 of Favorites, then you may not want to model it, but query for it instead.  Some JPA providers, such as EclipseLink allow you to add to OneToMany Collections without forcing instantiation, so in some cases, even if you model the relationship, you may not need to instantiate it.  But if you never intend to instantiate it, then there is little point having the relationship.  EclipseLink also supports a query cache, so even if you query it, you still may not require accessing the database every time.