简体   繁体   English

JPA:保留地图<String,Entity>

[英]JPA: Persisting a Map<String,Entity>

Could you help to persist a Map when String is not the key of the Entity mapped? 当String不是所映射实体的键时,是否可以帮助保留Map? For example: 例如:

class A {

   @Id
   long id;

   String code;
}

class B {

   @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
   @What magical combination of JPA annotations should I use here?! 
   Map<String,A> mapAByCode;

}

I've tried a lot of combinations of {@JoinTable,@MapKeyColumn,@JoinColumn,@JoinTable} annotations with no success and I'm going crazy... 我尝试了{@ JoinTable,@ MapKeyColumn,@ JoinColumn,@ JoinTable}批注的许多组合,但均未成功,我要疯了……

Thanks! 谢谢!

Since you seem to want to map your entities using the A.code value, @MapKey is what you are after. 由于您似乎想使用A.code值映射实体,因此@MapKey是您所追求的。 @MapKey allows you to define the value within the reference to use as the key for the map. @MapKey允许您定义引用内的值以用作地图的键。 As the javadoc states, it is required to be unique though or you will run into problems. 如javadoc所述,它必须是唯一的,否则您将遇到问题。

  @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
  @MapKey(name="code")
  Map<String,A> mapAByCode;

It seems that the problem is related to other map I'm using in the same class: 看来问题与我在同一课程中使用的其他地图有关:

@Entity
class A {

  @Id
  long id;

  String code;
}

@Entity
class B {

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    @JoinTable(name = "B_MAPABYID", joinColumns = @JoinColumn(name = "B_ID"))
    @MapKey(name="id")
    Map<Long,A> mapAById;

    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    @JoinTable(name = "B_MAPABYCODE", joinColumns = @JoinColumn(name = "B_ID"))
    @MapKey(name="code")
    Map<String,A> mapAByCode;

}

This configuration is not working for me, but if I set mapAById as transient all works fine. 此配置不适用于我,但是如果我将mapAById设置为瞬态,则一切正常。 Does it makes any sense for you? 这对您有意义吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM