Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

java - JPA: Store a list of integers in a single field

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;
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...