Thursday, 15 April 2010

java - How to persist an EnumSet (using two database tables)? -



java - How to persist an EnumSet (using two database tables)? -

i want represent set of options enumset in entity , one-to-many relation in database. how done properly? can find old (pre-annotations) answers or answers not using 2 tables.

i defined next tables:

class="lang-sql prettyprint-override">create table users ( id serial primary key, name varchar(255) not null unique ); create table user_options ( user_id int, user_option varchar(255), primary key (user_id, user_option), foreign key (user_id) references users(id) on delete cascade on update cascade );

this entity class:

class="lang-java prettyprint-override">@entity(name = "users") public final class user { @id @generatedvalue private int id; @column(nullable = false, unique = true) private string name; private final set<useroption> options; { this.options = enumset.noneof(useroption.class); } /* plain getter id included */ /* plain getter , setter name included */ @elementcollection(fetch = fetchtype.eager) @enumerated(enumtype.string) @collectiontable(name = "user_options" , joincolumns = @joincolumn(name = "user_id")) @column(name = "user_option", nullable = false) public set<useroption> getoptions() { homecoming this.options; } }

and of course of study enum:

class="lang-java prettyprint-override">public enum useroption { option_a, option_b, option_c; }

when start tomcat next exception:

class="lang-none prettyprint-override">org.hibernate.mappingexception: not determine type for: java.util.set, @ table: users, columns: [org.hibernate.mapping.column(options)]

this exception root of bunch of exceptions causing each other. causes javax.persistence.persistenceexception (unable build entitymanagerfactory), in turn causes dependency injection exceptions.

i admit i'm not versed plenty in jpa/hibernate understand i'm doing wrong. can help me out?

it turns out reply more simple thought. cannot mix jpa-annotation on instance variables , getters. annotations fine. changed entity class follows , works fine now.

class="lang-java prettyprint-override">@entity(name = "users") public final class user { @id @generatedvalue private int id; @column(nullable = false, unique = true) private string name; @elementcollection(fetch = fetchtype.eager) @enumerated(enumtype.string) @collectiontable(name = "user_options" , joincolumns = @joincolumn(name = "user_id")) @column(name = "user_option", nullable = false) private final set<useroption> options; { this.options = enumset.noneof(useroption.class); } /* plain getter id included */ /* plain getter , setter name included */ public set<useroption> getoptions() { homecoming this.options; } }

java hibernate jpa enums persistence

No comments:

Post a Comment