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;
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.
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.
@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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With