Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persist collection fields with hibernate

Using hibernate, how can I persist a class with a List<String> field?

Consider the following entity class:

@Entity
public class Blog {
    private Long id;
    private List<String> list;

    @Id
    @GeneratedValue
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }

    public List<String> getList() { return list; }
    public void setList(List<String> list) { this.list = list; }
}

However, when I attempt to save it, I get the following error:

[INFO] An exception occured while executing the Java class. null

Could not determine type for: java.util.List, at table: Blog, for columns: [org.hibernate.mapping.Column(list)]

I tried adding '@CollectionOfElements' to getList(), but then only the id is saved to the library. No corresponding column is created for the list.

Note: I'm just trying Hibernate, so I could use documentation links that we will help me understand the collection relationship management in Hibernate

like image 680
notnoop Avatar asked Sep 01 '09 05:09

notnoop


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.

Which technique is used by Hibernate to persist collections of embeddable types?

JPA + Hibernate - Persisting Collections of embeddable type by using @ElementCollection.

How do I persist a list in JPA?

Solution: Since JPA 2.0, you can use an element collection to persist a Collection of value types. You just need to annotate the attribute with @ElementCollection and the persistence provider will persist the elements of the Collection in an additional database table.


1 Answers

Have a look at This. Maybe it is of help.

Did you apply @CollectionOfElements as follows?

@org.hibernate.annotations.CollectionOfElements(
targetElement = java.lang.String.class

)

like image 175
shipmaster Avatar answered Oct 13 '22 15:10

shipmaster