Java - JPA @Basic and @Embedded annotations

前端 未结 3 2076
北海茫月
北海茫月 2020-12-07 17:38

I am learning JPA from this tutorial.

I have some confusions in understanding the following annotations:

  • @Basic
  • @Embedded
3条回答
  •  醉酒成梦
    2020-12-07 18:22

    @Basic

    The Basic annotation can be applied to a persistent property or instance variable of any of the following types:

    Java primitive types, wrappers of the primitive types, String, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and any other type that implements java.io.Serializable.

    The use of the Basic annotation is optional for persistent fields and properties of these types. If the Basic annotation is not specified for such a field or property, the default values of the Basic annotation will apply.

    Example:

    @Basic
    protected String name;
    

    and

    @Basic(fetch=LAZY)
    protected String getName() { 
        return name; 
    }
    

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

    Example 1:

    @Embedded    
    @AttributeOverrides({
           @AttributeOverride(name="startDate", column=@Column("EMP_START")),
           @AttributeOverride(name="endDate", column=@Column("EMP_END"))    
    })        
    public EmploymentPeriod getEmploymentPeriod() { ... }
    

    Example 2:

    @Entity
    public class Project {
        @EmbeddedId ProjectId id;
        //other fields
    }
    
    
    @Embeddable
    Class ProjectId {
        int departmentId;
        long projectId;
    }
    

    JSR Persistence Specification and Source reference

提交回复
热议问题