1

I have a LocalizedString Embeddable that looks like this:

@Embeddable
public class LocalizedString {

    @ElementCollection(fetch = FetchType.EAGER)
    private Map<String, String> stringMap;

    // getter, setter
}

and an Article class that is supposed to make use of the LocalizedString:

@Entity
public class Article {

    @Id
    @GeneratedValue
    private long id;

    @Embedded
    private LocalizedString title;

    @Embedded
    private LocalizedString text;

    // getter, setter
}

Generating the tables works just fine, but when I try to insert an Article I get the following exception:

Duplicate entry '1-test2' for key 'PRIMARY'

After looking at the database structure it's obvious why. Hibernate only generated one article_string_map table with the a primary key constraint over the article id and the key of the map.

Googling this problem led me to this question on SO and the answer to include the @AttributeOverride annotations:

@Entity
public class Article {

    @Id
    @GeneratedValue
    private long id;

    @AttributeOverride(name="stringMap",column=@Column(name="title_stringMap"))
    @Embedded
    private LocalizedString title;

    @AttributeOverride(name="stringMap",column=@Column(name="text_stringMap"))
    @Embedded
    private LocalizedString text;
}

This does not work either though, since Hibernate now complains about this:

Repeated column in mapping for collection:
test.model.Article.title.stringMap column: title_string_map

I do not understand what exactly is causing this error and I couldn't really translate the things I did find out about it to my specific problem.

My question is, what else do I need to fix to make LocalizedString work as an Embeddable? I'd also like to know why Hibernate is saying that I mapped title_string_map twice, even though I don't mention it twice in my entire project. Is there some kind of default mapping going on that I need to override?

How can I tell Hibernate to map this correctly?

(Also, I don't have a persistence.xml since I'm purely using annotations for configuration)

Community
  • 1
  • 1
mhlz
  • 3,497
  • 2
  • 23
  • 35

1 Answers1

0

I figured it out on my own.

In order to map a ElementCollection I had to use @AssociationOverride combined with the joinTable attribute. The working Article class looks like this now:

@Entity
public class Article {

    @Id
    @GeneratedValue
    private long id;

    @AssociationOverride(name = "stringMap", joinTable = @JoinTable(name = "title_stringMap"))
    @Embedded
    private LocalizedString title;

    @AssociationOverride(name = "stringMap", joinTable = @JoinTable(name = "text_stringMap"))
    @Embedded
    private LocalizedString text;

    // getters, setters
}
mhlz
  • 3,497
  • 2
  • 23
  • 35