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

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

问题描述

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

  @Entity 
public class Person {
@Embedded
public回家

@嵌入
公共地址工作;
}

公共类地址{
public String street;
...
}

在这种情况下,一个可以包含两个地址实例 - 家庭和工作。我使用Hibernate的实现JPA。当我使用Hibernate Tools生成模式时,它只嵌入一个 Address 。我想要的是两个嵌入的 Address 实例,每个实例的列名都被区分或预先添加了一些前缀(比如home和work)。我知道 @AttributeOverrides ,但这需要单独覆盖每个属性。如果嵌入式对象( Address )变大,因为每列都需要单独覆盖,这可能会变得很麻烦。 >解决方案

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



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


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

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.

解决方案

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.

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

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

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