tags:

views:

262

answers:

3

I am learning JPA from this tutorial.

I have some confusions in understanding the following annotations:

  • @Basic
  • @Embedded

Fields of an embeddable type default to persistent, as if annotated with @Embedded.

If the fields of embeddable types defualt to persistent, then why would we need @Embedded

A: 

To specify custom properties about the mapping.

escanda
+3  A: 

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

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() { ... }

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).

Pascal Thivent
Q1. If the fields or properties of embeddable types are by defualt persistent then why we need to add `@Embedded` annotation ? Q2. Can I use `@AttributeOverrides` annotation without `@Embedded` annotation? Could you please also throw some light on `@Basic`?
Yatendra Goel
Q1. Because @Embedded allows to override column definitions Q2. No I don't think so. There is a good example illustrating this here: http://www.redhat.com/docs/en-US/JBoss_Enterprise_Web_Platform/5.0.0/html/Hibernate_Annotations_Reference_Guide/ch02s02s02s03.html
Pascal Thivent
+1  A: 

In ORM mapping, the granularity of your object model can be finer than that of your database.

For example, you can have a Person record in your database which can be further decomposed to contain a reference to an Address object in your model. That's where the @Embedded and @Embeddable annotations come in. They simply state a relationship where one Entity can be stored as part of another.

As for the @Basic annotation, it's the simplest from of mapping which is applied by default to primitive types such as int and float and their wrappers as well as enums. More information can be had here: http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/entity.html#entity-mapping-property

James P.