views:

1116

answers:

3

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

A: 

Have a look at the Hibernate Annotations Documentation about Collections basically you have to tell the list in what relation it stands to.

@OneToMany(mappedBy="blog")
public List<String> getList() { return list; }

Then it should work.

Daff
I would get thw following error: '@OneToOne or @ManyToOne on uk.co.pookey.hibernate.model.Blog.list references an unknown entity: java.util.List
notnoop
That should work though. Did you import the Hibernate or the JPA annotation?
Daff
Imported JPA javax.persistence annotation
notnoop
+1  A: 

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

)

shipmaster
Thanks! New table is created to save the mapping
notnoop
A: 

Use a Serializable object seems to work better. Changing list property to ArrayList<String> seems to solve the problem.

notnoop