Coming off my way-too-popular question from yesterday:
Hibernate(JPA) mapping a HashMap
I'm trying to map a structure that is essentially the following:
Map<User, List< POJOWithComposite >>
Where User
is a basic model, similar to the following:
@Entity
public class User extends Model {
public String username;
public String password;
...
}
and POJOWithComposite
is another entity, that has some mapped entities and some primitives, similar to:
@Entity
public class POJOWithComposite extends Model {
public int someIntField;
public OtherModel compositeEntity;
...
}
The structure could be analogous to a shopping cart. So the User
holds the account info, the OtherModel
could be a purchasable item, and POJOWithComposite
is a shopping cart that holds items and quantities, say. My analogy breaks down a little when it comes to the main object, but humour me, and let's say for every session we add the shopping cart the user paid for to the list, which will then be archived, say.
Firstly, if the list belongs to each user I could just add it to the User
model, although I feel that this isn't very modular (i.e. the information isn't really user account information). ATM, this map sits in a utility-like shopping class, which takes care of matching shopping carts with shoppers, to save me from making the User
model too big. (Is there a better pattern to use here perhaps?)
Assuming that I continue down this road, Let's try and map this Map
. Ideally, I would like to be able to map it as is. Although I have had very little luck with that.
I happened upon some talk of mapping ArrayList
easily because it's Serializable
, although didn't manage to implement that here.
So I made a wrapper entity:
@Entity
public class POJOWithCompositeList extends Model {
@OneToMany
List<POJOWithComposite> list = new ArrayList<POJOWithComposite>();
}
This works. When I use this entity like this, I can map my new:
@ManyToMany
Map<User, POJOWithCompositeList>
Although I don't really like this solution because I add another mapped entity, i.e. the wrapping entity means another table in the database, which means another join every query etc...
So my two questions are:
- From the design perspective, is sticking this
Map
in a util class acceptable? - Assuming we do map the models like this, how can I improve the mapping?