JPA: Store a list of integers in a single field

It is not possible to store multiple values in a single field. Whats the reason behind storing them in a single field?

A way could be to use a field of type String and add all integers there in a comma separated list and join/explode in getters and setters:

private String vals;

public setVals(int vals[])
{
     // this.vals = Iterate vals[] and create a comma separated string
}

public int[] getVals()
{
    // vals.split(",") to get a list of Strings, then typecast/parse them to ints before returning
}

Using the @ElementCollection annotation and @CollectionTable to control the mappings requires a separate table to store the values in.

@ElementCollection
private Collection<Integer> integers;

Read more about element collections on on http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection

Similar question here Does JPA @ElementCollection annotation always produce an one-to-many relationship?


You can create a converter and use it with the annotation @Converter.

This converter must implement AttributeConverter which is a generic interface with two methods convertToDatabaseColumn and convertToEntityAttribute.

It is pretty easy to work with, you can check here: jpa independent custom type mapping / javax.persistence.x alternative to org.hibernate.annotations.Type and org.hibernate.annotations.TypeDef