
EJB实体操作的高级特性
继承映射
@DiscriminatorColumn(name="DISC", discriminatorType=STRING,length=20)//指定区别父子类的表述符的名字、类型和长度 @DiscriminatorValue("CUSTOMER")//指定本类描述符的值 以上两个标注只适用于所有类建一个表的情况。
@Inheritance(strategy=JOINED|SINGLE_TABLE|TABLE_PER_CLASS) SINGLE_TABLE也就是所有类建一张表 JOINED也就是每个类建一个表。 TABLE_PER_CLASS只针对对具体类建表。
@MappedSuperclass//映射子类型,这个标注没有属性
@AttributeOverride @AttributeOverrides
一对一关联
@OnetoOne(targetEntity="",cascade="CascadeType.ALL|MERGE|PERSIST|REFRESH|REMOVE", fetch="FetchType.EAGER|LAZY", mappedBy="",optional="true|false") cascade级联设置, ALL对主对象的增删该操作,都会级联到子对象 PERSIST只有对主对象进行增加操作时,才级联到子对象 REMOVE只有对主对象进行删除操作时,才级联到子对象 MERGE只有对主对象进行修改操作时,才级联到子对象 REFRESH只有对主对象进更新操作时,才级联到子对象
fetch加载策略,FetchType.EAGER是采取立即加载策略,FetchType.LAZY是采用延迟加载。 mappedBy,是指定拥有关系的属性,只需要在关联的反方向(非主对象)一端指定使用mappedBy的属性。
@JoinColumn(name="",referencedColumnName="",unique="true|false",nullable="true|false",updateable="true|false",table="...")//用来指定根据类关系映射到表后和其他表关联的列名,以及关联的列名,以及本列的属性 name属性指定类中属性对应的列名,默认为属性名 referencedColumnName属性指定类对应的表中的关联引用的列的列名。 nullable属性指定类中属性对应的列是否可空,默认为true updateable="true|false"属性指定类中该属性是否会出现在update语句中,也就是会不会被修改,默认为true可以被修改。
table属性指定类中有关联属性的列所对应的表,默认为实体类所对应的表。 @PrimaryKeyJoinColumn主键关联
例: 引用外键 @OneToOne(optional=false) @JoinColumn(name="CUSTREC_ID", unique=true, nullable=false, updatable=false) public CustomerRecord getCustomerRecord() { return customerRecord; }
@OneToOne(optional=false, mappedBy="customerRecord") public Customer getCustomer() { return customer; }
共享主键 @Entity public class Employee { @Id @OneToOne @PrimaryKeyJoinColumn Integer id; EmployeeInfo info; ... }
On EmployeeInfo class:
@Entity public class EmployeeInfo { @Id Integer id; ... }
多对多关联 @OneToMany(targetEntity="",cascade="CascadeType.ALL|MERGE|PERSIST|REFRESH|REMOVE", fetch="FetchType.EAGER|LAZY", mappedBy="")
@OneToMany(cascade=ALL, mappedBy="customer") public Set getOrders() { return orders; }
In Order class:
@ManyToOne @JoinColumn(name="CUST_ID", nullable=false) public Customer getCustomer() { return customer; }
@OneToMany(targetEntity=com.acme.Order.class, cascade=ALL, mappedBy="customer") public Set getOrders() { return orders; }
In Order class:
@ManyToOne @JoinColumn(name="CUST_ID", nullable=false) public Customer getCustomer() { return customer; }