Java - JPA @Basic和@Embedded注释 [英] Java - JPA @Basic and @Embedded annotations
问题描述
我正在从本教程。
我对理解以下注释有一些困惑:
I have some confusions in understanding the following annotations:
-
@Basic
-
@Embedded
@Basic
@Embedded
可嵌入类型的字段默认为持久化,就像使用@Embedded注释一样。
Fields of an embeddable type default to persistent, as if annotated with @Embedded.
如果embeddable类型的字段默认为持久性,那么为什么我们需要 @Embedded
注释
If the fields of embeddable types default to persistent, then why would we need the @Embedded
annotation
推荐答案
@Embeddable
注释允许指定存储实例的类作为拥有实体的固有部分。此注释具有无属性。
The @Embeddable
annotation allows to specify a class whose instances are stored as intrinsic part of the owning entity. This annotation has no attributes.
@Embeddable
public class EmploymentPeriod {
java.util.Date startDate;
java.util.Date endDate;
...
}
@Embedded
注释用于指定实体的持久字段或属性,该实体的值是可嵌入类的实例。默认情况下, @Embeddable
类中指定的列定义适用于拥有实体的表,但您可以使用 > @AttributeOverride
:
The @Embedded
annotation is used to specify a persistent field or property of an entity whose value is an instance of an embeddable class. By default, column definitions specified in the @Embeddable
class apply to the table of the owning entity but you can override them using@AttributeOverride
:
@Embedded
@AttributeOverrides({
@AttributeOverride(name="startDate", column=@Column(name="EMP_START")),
@AttributeOverride(name="endDate", column=@Column(name="EMP_END"))
})
public EmploymentPeriod getEmploymentPeriod() { ... }
关于可选的 @Basic
注释,您可以使用它将获取类型配置为 LAZY
并使用可选
属性将映射配置为禁止空值(对于非基本类型)。
Regarding the optional @Basic
annotation, you may use it to configure the fetch type to LAZY
and to configure the mapping to forbid null values (for non primitive types) with the optional
attribute.
@Basic(fetch=LAZY)
protected String getName() { return name; }
您也可以将它放在字段或属性上以明确标记为持久性(用于文档目的) )。
You can also place it on a field or property to explicitly mark it as persistent (for documentation purpose).
这篇关于Java - JPA @Basic和@Embedded注释的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!