JPA 多个嵌入字段 [英] JPA Multiple Embedded fields

查看:28
本文介绍了JPA 多个嵌入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JPA 实体类是否可以包含两个嵌入的 (@Embedded) 字段?一个例子是:

Is it possible for a JPA entity class to contain two embedded (@Embedded) fields? An example would be:

@Entity
public class Person {
    @Embedded
    public Address home;

    @Embedded
    public Address work;
}

public class Address {
    public String street;
    ...
}

在这种情况下,一个 Person 可以包含两个 Address 实例 - home 和 work.我在 Hibernate 的实现中使用 JPA.当我使用 Hibernate Tools 生成模式时,它只嵌入了一个 Address.我想要的是两个嵌入的 Address 实例,每个实例都有其列名,或者以一些前缀(例如 home 和 work)为前缀.我知道 @AttributeOverrides,但这需要单独覆盖每个属性.如果嵌入的对象 (Address) 变大,这会变得很麻烦,因为每一列都需要单独覆盖.

In this case a Person can contain two Address instances - home and work. I'm using JPA with Hibernate's implementation. When I generate the schema using Hibernate Tools, it only embeds one Address. What I'd like is two embedded Address instances, each with its column names distinguished or pre-pended with some prefix (such as home and work). I know of @AttributeOverrides, but this requires that each attribute be individually overridden. This can get cumbersome if the embedded object (Address) gets big as each column needs to be individually overridden.

推荐答案

如果您想在同一个实体中两次使用相同的可嵌入对象类型,则默认列名将不起作用:至少其中一列必须明确.Hibernate 超越了 EJB3 规范,允许您通过 NamingStrategy 增强默认机制.DefaultComponentSafeNamingStrategy 是对默认 EJB3NamingStrategy 的一个小改进,即使在同一实体中使用两次,它也允许默认嵌入的对象.

If you want to have the same embeddable object type twice in the same entity, the column name defaulting will not work: at least one of the columns will have to be explicit. Hibernate goes beyond the EJB3 spec and allows you to enhance the defaulting mechanism through the NamingStrategy. DefaultComponentSafeNamingStrategy is a small improvement over the default EJB3NamingStrategy that allows embedded objects to be defaulted even if used twice in the same entity.

来自 Hibernate 注释文档:http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e714

From Hibernate Annotations Doc: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#d0e714

这篇关于JPA 多个嵌入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆