Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to persist a List of Strings in Hibernate?

I seem to have problems with mapping a List in Hibernate. In our project there a class Card with contains a class Answer with Answer containing a List<String>.

Is a List<String> mappable by Hibernate using annotations? I mean, since it does not have the @Entity annotation?

Regards

like image 677
TeaOverflow Avatar asked May 03 '11 08:05

TeaOverflow


People also ask

How do you persist objects in Hibernate?

All classes should contain an ID in order to allow easy identification of your objects within Hibernate and the database. This property maps to the primary key column of a database table. All attributes that will be persisted should be declared private and have getXXX and setXXX methods defined in the JavaBean style.

Can we save list of objects in Hibernate?

To save list of object, you need to iterate by objects, something like this -> How to insert multiple rows into database using hibernate? Save this answer. Show activity on this post. I would further recommend to use another Hibernate command to avoid an Out Of Memory error...

Which annotation is used to persist a collection of value types?

The @Cascade annotation enables Hibernate to persist the collections associated with the main instance.

What is the difference between Merge and persist in Hibernate?

Persist should be called only on new entities, while merge is meant to reattach detached entities. If you're using the assigned generator, using merge instead of persist can cause a redundant SQL statement.


1 Answers

Use @ElementCollection:

@ElementCollection @CollectionTable(name="Nicknames", joinColumns=@JoinColumn(name="user_id")) @Column(name="nickname") public List<String> getNicknames() { ... }  

Source: 7.2.3. Collections of basic types and embeddable objects

like image 65
Sean Patrick Floyd Avatar answered Oct 02 '22 22:10

Sean Patrick Floyd