Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPA: Store a list of integers in a single field

Tags:

Is it possible to store a list of integers in a single field of the respective entity table with standard JPA 2?

@Entity
@Table(name="tbl_myentities")
public class MyEntity {

@ElementaryCollection
@Column(name="vals") // in table tbl_myentities
private List<Integer> vals;
like image 731
Michael Avatar asked Jan 30 '12 14:01

Michael


People also ask

How to store list of strings in single column using JPA?

The easiest way to store list of strings in a single database column is to store them as comma separated strings. We use JPA 2.1 Attribute Converter feature to convert list of string to comma separated string while storing into database and vice versa while reading from the database.

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.

What is @transient in JPA?

@Transient annotation in JPA or Hibernate is used to indicate that a field is not to be persisted or ignore fields to save in the database. @Transient exist in javax. persistence package. It is used to annotate a property or field of an entity class, mapped superclass, or embeddable class.


2 Answers

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?

like image 162
MrKiane Avatar answered Sep 22 '22 08:09

MrKiane


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

like image 40
g__n Avatar answered Sep 19 '22 08:09

g__n