JPA @Embedded 注释是强制性的吗?

Is the JPA @Embedded annotation mandatory?

我已经尝试省略 @Embedded 注释,但字段仍然嵌入在table 中。我找不到任何可以说明 @Embedded 注释是可选的内容。

还是不是可选的吗?

以下代码

@Embeddable
public class Address {
    String city;
    String street;
}

@Entity
public class Person {
    String name;
    @Embedded // it seems that it works even if this annotation is missing!?
    Address address;
}

生成始终相同的 table

person
    name
    city
    street

即使我指定@Embedded


我的配置:


JPA 规范说:

http://docs.oracle.com/javaee/7/api/javax/persistence/Embedded.html

@javax.persistence.Embedded

Specifies a persistent field or property of an entity whose value is an instance of an embeddable class. The embeddable class must be annotated as Embeddable.

http://docs.oracle.com/javaee/7/api/javax/persistence/Embeddable.html

@javax.persistence.Embeddable

Specifies a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity. Each of the persistent properties or fields of the embedded object is mapped to the database table for the entity.

Embedded-Embeddable 不是强制性的,但它为您提供了实体关系的良好 OOP 视角。另一种方法是使用 OneToOne 映射。但在这种情况下,实体将被写入单独的 table(而在嵌入的情况下,它可以写入数据库中单独的 table)。

在使用 Hibernate 的情况下,无论您是注释字段本身(如 @Embedded)还是注释引用的 class(如 @Embeddable)都没有关系。至少需要两者之一才能让 Hibernate 确定类型。

并且在 Hibernate 文档中有一个关于此的(隐式)声明,请看这里: http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/mapping.html#mapping-declaration-component

它说:

The Person entity has two component properties, homeAddress and bornIn. homeAddress property has not been annotated, but Hibernate will guess that it is a persistent component by looking for the @Embeddable annotation in the Address class.