2

我需要将地图的值分配给我的实体,但 jpa 尝试将孔对象保存为字节数组。

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

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

我认为这并不难,但我在网上找不到任何例子。请你帮助我好吗?非常感谢!

4

1 回答 1

3

带有注释的关联@ElementCollection对以下映射类型有效:

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

@OneToMany用/注释的关联@ManyToMany对以下映射类型有效:

  • Map<Basic,Entity>(这是你的情况)
  • Map<Embeddable,Entity>
  • Map<Entity,Entity>

根据上述规则,实体可能如下所示:

@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;
}

请注意,和之间的双向关联ImageSet.imagesImage.container可选的,但删除它会在数据库中创建一个额外的表。

于 2015-04-10T12:38:24.420 回答