Frage

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;

Thanks

War es hilfreich?

Lösung

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?

Andere Tipps

You can store all the vals in a String field, separated with a comma, and change associated getter and setter like that :

public List<Integer> getVals() {
    List<Integer> lstVals = new ArrayList<Integer>();
    int val = 0;

    for(String field : this.vals.split(",")) {
        try {
            val = Integer.parseInt(field);
        }
        // If the String contains other thing that digits and commas
        catch (NumberFormatException e) {
        }
        lstVals.add(val);
    }

    return lstVals;
}

public void setVals(List<Integer> vals) {
    String newVals = "";
    for(int i : vals) {
        newVals.concat(String.valueOf(i));
    }
    this.vals = newVals;
}

You can create a converter and use 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.

I don't think that's possible. Because you can not have a column in a database table that allows you to store list of integers.

What you can do is use a string type field instead of list of integers -

@Column(name="vals") // in table tbl_myentities
private String vals;

And do the conversion to string from list of integers and back manually before you save your entity and after you have read your entity.

Maybe a @Lob could suit you ? (despite what it imply)

@Lob
ArrayList<String> vals;

(note that your collection must be explicitly an ArrayList)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top