一个实体类必须遵循一下要求:
1. 类必须用javax.persistence.Entity注释
2. 类必须有一个public或protected的无参数构造器。可以有其他的构造器。
3. 类不准许声明为final。
4. 实体类可以继承实体类也可以继承非实体类。非实体类可以继承实体类。
JPA中可以持久化的字段类型:
- Java原始类型
- Java.lang.String
- 可序列化类型
- Wrappersof Java primitive types
- java.math.BigInteger
- java.math.BigDecimal
- java.util.Date
- java.util.Calendar
- java.sql.Date
- java.sql.Time
- java.sql.TimeStamp
- User-definedserializable types
- byte[]
- Byte[]
- char[]
- Character[]
- 枚举类型Enumerated Types
- 其他实体或实体集合
- 内嵌类
基本实体映射
@Entity
@SecondaryTable(name = "SALARY")
public class Employee implements Serializable {
@Id
@Column(name = "EMP_ID")
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
@Basic
@Version
private long version;
@Basic
@Column(name = "F_NAME")
private String firstName;
@Basic
@Column(name = "L_NAME")
private String lastName;
@Basic
@Column(name = "GENDER")
@Enumerated(EnumType.STRING)
private Gender gender = Gender.Male;
@Column(table = "SALARY")
private double salary;
……
}
抽象的实体注释
@Entity
public abstract class Employee {
@Id
protectedInteger employeeId;
...
}
@Entity
public class FullTimeEmployee extends Employee {
protectedInteger salary;
...
}
@Entity
public class PartTimeEmployee extends Employee {
protected FloathourlyWage;
}
超类映射
@MappedSuperclass
public class Employee {
@Id
protected Integer employeeId;
...
}
@Entity
public class FullTimeEmployee extends Employee {
protected Integer salary;
...
}
@Entity
public class PartTimeEmployee extends Employee {
protected Float hourlyWage;
...
}
内嵌实体类映射
@Embeddable
//內嵌到其他實體,與其共享identity
public class EmploymentPeriod {
//@Temporal必須為java.util.Date and java.util.Calendar類型的字段或屬性註釋,
//而且只能為這些類型的字段或屬性註釋。
@Temporal(TemporalType.DATE)
private Calendar startDate;
@Temporal(TemporalType.DATE)
private Calendar endDate;
… …
}
public classEmployee implements Serializable {
… …
@Embedded
@AttributeOverrides( {
@AttributeOverride(name = "startDate", column = @Column(name = "START_DATE")),
@AttributeOverride(name = "endDate", column = @Column(name = "END_DATE")) })
private EmploymentPeriod period;
… …
}