Entities
对应的其实就是关系型数据库中的一行
1. 声明Entity类的要求
1)需要标明@Entity
2)类必须含有一个public或者protected的无参构造函数
3)类不能是final,其properties与方法也不能为final
4)Entity类和非Entity可以互为集成关系
5)Entity中的类成员变量访问级别必须设为private,protected,package-private,然后通过类方法对类成员变量进行访问、修改
2. Entity中的fields与property
1)field
如果field没有标明为@Transient,则会存储于数据库
2)property(Persistent Property)
遵循javabean规范,getProperty, setProperty, isProperty
3)collection
只能用Collection, Set, List, Map。
如果使用的是基础类型,则需要标明为@ElementCollection,其中需要声明targetClass和fetch。fetch默认是lazy的。
@Entity public class Person { ... @ElementCollection(fetch=EAGER) protected Set<String> nickname = new HashSet(); ... }Map类型(这部分内容相对较多)
4)property和field的校验
@Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\." + "[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@" + "(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9]" + "(?:[a-z0-9-]*[a-z0-9])?", message = "{invalid.email}") protected String email;
3. Entity中的主键
1)基础类型(不包含float,double)
2)符合主键(内容相对较多)
3. Entity中的关系
@OneToOne\@OneToMany\@ManyToOne\@ManyToMany
4. Entity中关系的方向
中间非常重要的是需要区分Entity中关系的方向,一种是单向(unidirectional),另一种是双向(bidirectional)。owning side决定如何对数据库进行更新。
1)bidirectional
在双向关系中,有一方是owning side,还有一个是reverse side。
规则如下:
a)通过mappedBy来指明owning side,如User和Account之间的关系,这样user就是owning
@OneToOne(mappedBy = "user")
private Account account;
@OneToOne
@JoinColumn(name = "USER_ID", unique = true, nullable = false)
private User user;
b)@ManyToOne不能设置mappedBy,因为many方会一直作为owning side
c)@OneToOne的owning side是含有外键的一方(这个和mappedBy如果不一致,会怎么样?)
d)@ManyToMany其中任何一方都可以作为owning side
2) unidirectional
3)query
4)cascade
ALL/DETACH/MERGE/PERSIST/REFRESH/REMOVE
5.Orphan Delete
@OneToMany(mappedBy="customer", orphanRemoval="true") public List<CustomerOrder> getOrders() { ... }
6.Embeddable Class
@Embeddable public class ZipCode { String zip; String plusFour; ... }
@Entity public class Address { @Id protected long id String street1; String street2; String city; String province; @Embedded ZipCode zipCode; String country; ... }
参考资料:https://docs.oracle.com/javaee/7/tutorial/doc/persistence-intro001.htm#BNBQA