Search code examples
eclipselinkjava-ee-7jpa-2.1glassfish-4.1

JPA ElementCollection Map<Integer, Entity>


i need to assign the value of the map to my entity but jpa tries to save the hole object as an byte array.

@Entity
public class ImageSet {
    ...
    @ElementCollection
    private Map<Integer, Image> images = new LinkedHashMap<>();
}

@Entity
public class Image {
    ...
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
}

I think it is not that hard but i cant find any examples online. Could you please help me? thank you very much!


Solution

  • Association annotated with @ElementCollection is valid for the following mapping types:

    • Map<Basic,Basic>
    • Map<Basic,Embeddable>
    • Map<Embeddable,Basic>
    • Map<Embeddable,Embeddable>
    • Map<Entity,Basic>
    • Map<Entity,Embeddable>

    Association annotated with @OneToMany / @ManyToMany is valid for the following mapping types:

    • Map<Basic,Entity> (this is your case)
    • Map<Embeddable,Entity>
    • Map<Entity,Entity>

    According to the above rules the entities may look as follows:

    @Entity
    public class ImageSet {
        ...
        @OneToMany(mappedBy="container")
        @MapKey //map key is the primary key
        private Map<Integer, Image> images = new LinkedHashMap<>();
    }
    
    @Entity
    public class Image {
        ...
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Long id;
    
        @ManyToOne
        private ImageSet container;
    }
    

    Note that bidirectional association between ImageSet.images and Image.container is optional, but removing it would create an additional table in the database.