为了将我的域模型与持久性机制分离,我使用 XML 来配置从域模型到数据库实体的映射。 我有这个实体:
public class Tenant {
long id;
Map<String, AuthApp> authApps;
...
}
这个值对象:
public class AuthApp {
String authCode;
int durationInDays;
...
}
值对象本身没有生命周期,它取决于实体。 我在 RDBMS 中创建两个表:“tenant”和“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 提供程序。
最佳答案
解决了!感谢 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>
......
关于java - 如何在jpa中将Map<String, MyValueObject>与xml映射?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48005780/