开发者

Trouble creating unique table of Strings when persisting List<String>

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> s开发者_JAVA百科trings = 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.


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.


Instead of using Vector, use HashSet

So perhaps do:

private Set<String> strings = new HashSet<String>();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜