简体   繁体   English

JPA Multiple Embedded字段

[英]JPA Multiple Embedded fields

Is it possible for a JPA entity class to contain two embedded ( @Embedded ) fields? JPA实体类是否可以包含两个嵌入( @Embedded )字段? 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. 在这种情况下, Person可以包含两个Address实例 - home和work。 I'm using JPA with Hibernate's implementation. 我正在使用JPA和Hibernate的实现。 When I generate the schema using Hibernate Tools, it only embeds one Address . 当我使用Hibernate Tools生成模式时,它只嵌入一个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). 我想要的是两个嵌入的Address实例,每个实例的列名都有区别或预先设置了一些前缀(例如家庭和工作)。 I know of @AttributeOverrides , but this requires that each attribute be individually overridden. 我知道@AttributeOverrides ,但这需要单独覆盖每个属性。 This can get cumbersome if the embedded object ( Address ) gets big as each column needs to be individually overridden. 如果嵌入对象( Address )变大,因为每个列都需要单独覆盖,这会很麻烦。

The generic JPA way to do it is with @AttributeOverride. 通用的JPA方法是使用@AttributeOverride。 This should work in both EclipseLink and Hibernate. 这应该在EclipseLink和Hibernate中都有效。

@Entity 
public class Person {
  @AttributeOverrides({
    @AttributeOverride(name="street",column=@Column(name="homeStreet")),
    ...
  })
  @Embedded public Address home;

  @AttributeOverrides({
    @AttributeOverride(name="street",column=@Column(name="workStreet")),
    ...
  })
  @Embedded public Address work;
  }

  @Embeddable public class Address {
    @Basic public String street;
    ...
  }
}

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. Hibernate超越了EJB3规范,允许您通过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. DefaultComponentSafeNamingStrategy是对默认EJB3NamingStrategy的一个小改进,即使在同一实体中使用两次,也允许默认嵌入对象。

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

When using Eclipse Link, an alternative to using AttributeOverrides it to use a SessionCustomizer. 使用Eclipse Link时,使用AttributeOverrides的替代方法是使用SessionCustomizer。 This solves the issue for all entities in one go: 这一次解决了所有实体的问题:

public class EmbeddedFieldNamesSessionCustomizer implements SessionCustomizer {

@SuppressWarnings("rawtypes")
@Override
public void customize(Session session) throws Exception {
    Map<Class, ClassDescriptor> descriptors = session.getDescriptors();
    for (ClassDescriptor classDescriptor : descriptors.values()) {
        for (DatabaseMapping databaseMapping : classDescriptor.getMappings()) {
            if (databaseMapping.isAggregateObjectMapping()) {
                AggregateObjectMapping m = (AggregateObjectMapping) databaseMapping;
                Map<String, DatabaseField> mapping = m.getAggregateToSourceFields();

                ClassDescriptor refDesc = descriptors.get(m.getReferenceClass());
                for (DatabaseMapping refMapping : refDesc.getMappings()) {
                    if (refMapping.isDirectToFieldMapping()) {
                        DirectToFieldMapping refDirectMapping = (DirectToFieldMapping) refMapping;
                        String refFieldName = refDirectMapping.getField().getName();
                        if (!mapping.containsKey(refFieldName)) {
                            DatabaseField mappedField = refDirectMapping.getField().clone();
                            mappedField.setName(m.getAttributeName() + "_" + mappedField.getName());
                            mapping.put(refFieldName, mappedField);
                        }
                    }

                }
            }

        }
    }
}

}

In case you are using hibernate you can also use a different naming scheme which adds unique prefixes to columns for identical embedded fields. 如果您正在使用休眠,您还可以使用不同的命名方案,为相同的嵌入字段的列添加唯一的前缀。 See Automatically Add a Prefix to Column Names for @Embeddable Classes 请参阅自动为@Embeddable类的列名添加前缀

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

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