'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



Solution 1:[1]

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.

Solution 2:[2]

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

Solution 3:[3]

 package com.company.directDataLoader.model.admin;

import java.util.Arrays;
import java.util.Collection;
import javax.persistence.AttributeConverter;

import static java.util.Collections.emptyList;

public class StringListConverter implements AttributeConverter<Collection<String>, String> {
    private static final String SPLIT_CHAR = ";";

    @Override
    public String convertToDatabaseColumn(Collection<String> stringList) {
        return stringList != null ? String.join(SPLIT_CHAR, stringList) : "";
    }

    @Override
    public Collection<String> convertToEntityAttribute(String string) {
        return string != null ? Arrays.asList(string.split(SPLIT_CHAR)) : emptyList();
    }
}

In the entity class:

@Column(name="table_keys")
@Convert(converter = StringListConverter.class)
private Collection<String> tableKeys;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Daff
Solution 2 notnoop
Solution 3 Barak Kedem