views:

83

answers:

2

Suppose I have an entity:

@Entity
public class AnEntity implements Serializable{
   @ElementCollection
   private List<String> strings = new Vector<String>();
// other stuff
}

I am using EclipseLink(JPA 2.0).

The strings in this List may have the same values in many AnEntity objects. That is to say, many AnEntity objects may reference the same strings.

The problem is that the default mapping that @ElementCollection provides leaves many duplicates in the table of strings (ANENTITY_STRINGS). How can I map this so that when I save the list of strings, is saves the values uniquely so that i don't have a massive table of duplicate strings?


I should add that I have tried using "placeholder" classes, that have a single member that is the string. Unfortunately, doing it this way leaves the data in the associated table completely unreadable, I am sure it's getting saved as a blob or lob. So, for instance I did something like this, instead of using List:

@ElementCollection
@ManyToMany
private List<StringWrapperClass> strings = new Vector<StringWrapperClass>();

And then my Entity looks something like:

@Entity
public class StringWrapperClass implements Serializable {
    private String string;
   // other stuff, getters, setters, id, etc
}

But as I said, that puts just bytes in ANENTITY_STRINGS. I can't imagine that is a "right" way to do this.

A: 

Instead of using Vector, use HashSet

So perhaps do:

private Set<String> strings = new HashSet<String>();
Andrew Dyster
That did not work, the persisted list still has many duplicates. To be clear, the Entity itself won't have duplicate string in it's list, it is the table itself with all the duplicates.
J_Y_C
+1  A: 

So, you want to create a mapping where each AnEntity has many strings, and each string can belong to many AnEntities. Then you should use @ManyToMany, because it's a many-to-many relationship.

axtavt
I thought that too, but I still end up with many duplicates in the ANENTITY_STRING table. This can be done pretty easily using just SQL, but I am trying to build this using just JPA 2.0 to help increase DB portability.
J_Y_C
@J_Y_C: I can't see how it can be done in SQL without duplicates. You will have duplicates either in the table of strings (for one-to-many relationship) or in the join table (for many-to-many relationship)
axtavt