【问题标题】:How to map Map<String, MyValueObject> with xml in jpa?如何在 jpa 中使用 xml 映射 Map<String, MyValueObject>?
【发布时间】:2018-06-08 21:38:06
【问题描述】:

为了将我的域模型与持久性机制分离,我使用 XML 来配置从我的域模型到数据库实体的映射。 我有这个实体:

public class Tenant {
   long id;
   Map<String, AuthApp> authApps;
   ...
}

还有这个值对象:

public class AuthApp {
   String authCode;
   int durationInDays;
   ...
}

值对象本身没有生命周期,它依赖于实体。 我在我的 RDBMS 中创建了两个表,“租户”和“auth_app”。 谁能指导我如何为这种情况编写 JPA xml? 到目前为止我编写的 XML 是这样的:

<entity class="Tenant">
  <table name="tenant"/>
  <attributes>
    <id name="id"><generated-value strategy="AUTO" /></id>
    <element-collection name="authApp">
      <map-key name="app_id"/>
      <collection-table name="auth_app">
        <join-column name="tenant_id" referenced-column-name="id"/>
      </collection-table>
    </element-collection>
  </attributes>
</entity>

不知道对不对,如何继续。

顺便说一句,我使用 hibernate 作为 JPA 提供程序。

【问题讨论】:

  • "AuthApp" 大概是一个实体呢?还是您使用属性转换器来持久化它?
  • @DN1 不,正如我上面提到的,它不是实体而是值对象。而且我没有使用转换器,我想知道它可以在这种情况下工作。
  • 如果它不支持 JPA(实体,可嵌入),那么除非您提供 @AttributeConverter 将(AuthApp 的)多个字段转换为存储表的单个列值,否则您无法持久保存它地图。

标签: java xml hibernate jpa


【解决方案1】:

解决了!感谢 DN1 的评论,我知道“值对象”是 JPA 语义中的“可嵌入”。因此,将“AuthApp”定义为“可嵌入”,使用“map-key-column”而不是“map-key”,完成。 整个过程是这样的:

<entity class="Tenant">
  <table name="tenant"/>
  <attributes>
    <id name="id"><generated-value strategy="AUTO" /></id>
    <element-collection name="authApp" target-class="AuthApp">
      <map-key-column name="app_id"/>
      <collection-table name="auth_app">
        <join-column name="tenant_id" referenced-column-name="id"/>
      </collection-table>
    </element-collection>
  </attributes>
</entity>
<embeddable class="AuthApp">
   <attributes>
       ......
   </attributes>
</embeddable>
......

【讨论】:

    猜你喜欢
    • 2011-10-22
    • 2010-10-25
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-08-31
    • 1970-01-01
    • 2011-10-20
    • 1970-01-01
    相关资源
    最近更新 更多