JPA mapping for a List or Set<String>
@ElementCollection has been introduced in JPA v 2.0: the mapping you've done is correct. However make sure the maven hibernate plugin you use is at the correct version. Hibernate itself is compliant with JPA 2.0 starting at version 3.5.
Blablalux
Updated on June 06, 2022Comments
-
Blablalux almost 2 years
Being new to ORM, I'd like to find a way to define a simple (meaning without an additional entity) mapping for a list (or a set) of strings within an entity. I found this sample:
import java.util.Set; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Book { @Id @GeneratedValue private Long id; @ElementCollection @CollectionTable(name = "tags") private Set<String> tags; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Set<String> getTags() { return tags; } public void setTags(Set<String> tags) { this.tags = tags; } }
which seems to fit my needs. However, processing this class with Eclipse's
hibernate3-maven-plugin:2.2:hbm2ddl
, I end up with the following error:[ERROR] Failed to execute goal org.codehaus.mojo:hibernate3-maven-plugin:2.2:hbm2ddl (default) on project test-database: Execution default of goal org.codehaus.mojo:hibernate3-maven-plugin:2.2:hbm2ddl failed: Could not determine type for: java.util.Set, at table: Book, for columns: [org.hibernate.mapping.Column(tags)] -> [Help 1]
Specifying
@ElementCollection(targetClass=String.class)
did not help. Adding a column definition to thetags
field (@Column(name = "tags", columnDefinition="character varying (255)", nullable = false)
) leads to a successful build but produces this SQL:create table Book ( id int8 not null, tags character varying (255) not null, primary key (id) );
which is not what I want, as I was expecting to end up with a
tags
table linked to the books table. Could someone point me to the right direction ? Thank you. -
dskfdskjgds over 8 yearsat least this is how i would handle it, but i'm also new to hibernate
-
Blablalux over 8 yearsThanks for your answer. Yes I know that your solution would fit. However, I specifically mentioned that I don't want to create an additional entity. I think this is the purpose of the
@ElementCollection
and@CollectionTable
annotations. -
Blablalux over 8 yearsW00t ! Thank you. Indeed the plugin used an old version of Hibernate. Updating the pom to a newer version solved the problem.