davin
davin

Reputation: 45525

Hibernate(JPA) mapping a HashMap

Prereading:

How to persist a HashMap with hibernate

My problem revolves aroung the following structure that I want to map with JPA:

Map<User, List<POJO>>

My POJO is very simple (no composite types etc., just some primitives).

How can I implement the advice in the linked question? How can I annotate only the List part with @Lob (When I just annotate the field I get a class cast error, because HashMap can't be cast to Blob, which is the root of my problem - that I can't annotate only the values part of the map)?

I'm not sure whether I need to make a wrapper type that implements Serializable that wraps the List, or it's enough to just use ArrayList, which is itself Serializable. And in any case, I'm not managing to persist this Map instance...

By the way, I'm open to advice about going about this all differently: I could just stick the List as a class member for each User, although I don't feel that it belongs there since it's not user data (like account data; name, address etc.). Its analogous to purchases, so I've placed them in a utility-like class (external to the User class) that takes care of these purchases, in order to have more modular models. I would like to hear advice as to whether or not this sounds sensible.

Any helpful advice will be rewarded with imaginary cookies (and upvotes, obviously).
They're fat free in a very non-imaginary sense.

Cheers.

Upvotes: 4

Views: 3664

Answers (1)

ThomasRS
ThomasRS

Reputation: 8287

If you have a Map, you probably have a one-to-many relationship. Stick your list in User and make your POJO an entity, and do not fool around with @Lob, the Map is a disaster waiting to happen (hash value / equals issues) and does not give a clean database mapping.

Upvotes: 2

Related Questions