2

I want to persist a List of Embeddable Objects in an Entity. But without creating a new Table for the Objects in the List.

I want to persist the Entity in a way that the List of coordinates is serialized to a String and saved in the column named "coordinates" of the Entity Entity_A.

I know that i shouldn't do this because it's bad design. But in this case it is needed.

My Attempt to do it:

@Entity
class Entity_A implements Serializable {
    //... 

    private List<Coordinate> coordinates;
}

@Embeddable
class Coordinate implements Serializable {
    private Float lat;
    private Float lng;
    private Float alt;
}

It doesn't work. i don't get any error.

Do you have any ideas how i can do it?

Edit:

Coordinate needs to be embeddable, because i use it elsewhere.

Laokoon
  • 1,241
  • 4
  • 24
  • 47
  • 1
    Do not make Coordinate embeddable unless you are using it elsewhere, and annotate the list with @Basic and use a serializable collection type instead of the List type. This will cause JPA to serialize the collection to the field directly. – Chris Aug 29 '13 at 14:16
  • It need to be Embeddable because i use it elsewhere. – Laokoon Aug 29 '13 at 14:41

1 Answers1

3

With JPA 2.1 it is possible:

annotate coordinates field with @ElementCollection

@ElementCollection    
private List<Coordinate> coordinates;

See more on http://en.wikibooks.org/wiki/Java_Persistence/ElementCollection

foal
  • 693
  • 7
  • 20