Hibernate Annotation 笔记
1.@Entity 标识实体
2.@Table (name = "tableName") //指定物理表
@Table(name="tbl_sky",
uniqueConstraints = {@UniqueConstraint(columnNames={"month", "day"})}//唯一性约束
)
3.@Embeddable 被声明的类可以嵌入其他实体中
public class Address {
private String street1;//persistent
public String getStreet1() { return street1; }
public void setStreet1() { this.street1 = street1; }
private hashCode; //not persistent
}
@Embedded 在实体中嵌入一个类型:常用的像名字,地址之类的
另,使用@AttributeOverrides标识覆盖原类中的属性取值,因为原实体可能引用的是其他字段。
@Embedded
@AttributeOverrides( {
@AttributeOverride(name="iso2", column = @Column(name="bornIso2") ),
@AttributeOverride(name="name", column = @Column(name="bornCountryName") )
} )
Country bornIn;
例子:
@Entity
class User {
@EmbeddedId
@AttributeOverride(name="firstName", column=@Column(name="fld_firstname")
UserId id;
Integer age;
}
@Embeddable
class UserId implements Serializable {//此处Serializable是必须的
String firstName;
String lastName;
}
4.@Access(AcessType.PROPERTY)
必须定义getter/setter方法才能实现持久化
还有另一种取值:AcessType.FILED,可以不定义getter/setter方法,也能实现持久化
此annotation也可以定义字段。
5.主键:
A.单键
@Id
@GeneratedValue (generator = "identity")
@GenericGenerator (name = "identity", strategy = "identity")
或者
@javax.persistence.SequenceGenerator(
name="SEQ_STORE",
sequenceName="my_sequence")
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_STORE")
其中:
strategy取值为:
AUTO - either identity column, sequence or table depending on the underlying DB
TABLE - table holding the id
IDENTITY - identity column
SEQUENCE - sequence
B.复合组键
@Entity
class Customer {
@EmbeddedId CustomerId id;
boolean preferredCustomer;
@MapsId("userId")//user.id与customerId.userId 使用相同的值
@JoinColumns({
@JoinColumn(name="userfirstname_fk", referencedColumnName="firstName"),
@JoinColumn(name="userlastname_fk", referencedColumnName="lastName")
})
@OneToOne User user;
}
@Embeddable
class CustomerId implements Serializable {
UserId userId;
String customerNumber;
}
@Entity
class User {
@EmbeddedId UserId id;
Integer age;
}
@Embeddable
class UserId implements Serializable {
String firstName;
String lastName;
}
6.字段设置:
@Column(
name="columnName";
boolean un(2)ique() default false;
boolean nu(3)llable() default true;
boolean in(4)sertable() default true;
boolean up(5)datable() default true;
String col(6)umnDefinition() default "";
String tab(7)le() default "";
int length(8)() default 255;
int precis(9)ion() default 0; // decimal precision
int scale((10)) default 0; // decimal scale
@Transient 非持久化字段
@Basic 持久化字段
@Basic(fetch = FetchType.LAZY) basic 用于定义property的fetch属性
@Enumerated(EnumType.STRING) 标识enum persisted as String in database
@Lob blob clob字段
@Formula("obj_length * obj_height * obj_width")//自定义输出
public long getObjectVolume()
7.Mapping关系
A.一对多或者一对一:
@OneToOne(cascade = CascadeType.ALL) 一对一关系,级联关系为all
@PrimaryKeyJoinColumn或者
指定关联外键
@JoinColumn(name="passport_fk")
Passport passport,
一对一的另一端只需@OneToOne(mappedBy = "passport"),passport为前一个实体声明的名字
@OneToMany(fetch = FetchType.LAZY , mappedBy = "adProduct")
@Cascade(value = {CascadeType.ALL,CascadeType.DELETE_ORPHAN})
@OrderBy(value = "id") //排序
B.多对一:
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="adPosition_id",nullable=false)
8.Fetch and Lazy
Annotations | Lazy | Fetch |
---|---|---|
@[One|Many]ToOne](fetch=FetchType.LAZY) | @LazyToOne(PROXY) | @Fetch(SELECT) |
@[One|Many]ToOne](fetch=FetchType.EAGER) | @LazyToOne(FALSE) | @Fetch(JOIN) |
@ManyTo[One|Many](fetch=FetchType.LAZY) | @LazyCollection(TRUE) | @Fetch(SELECT) |
@ManyTo[One|Many](fetch=FetchType.EAGER) | @LazyCollection(FALSE) | @Fetch(JOIN) |
9.Cascade
-
PERSIST
-
MERGE
-
REMOVE
-
REFRESH
-
DELETE
-
SAVE_UPDATE
10.缓存
缓存的注释写法如下,加在Entity的java类上:
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
缓存的方式有四种,分别为:
- CacheConcurrencyStrategy.NONE
- CacheConcurrencyStrategy.READ_ONLY,只读模式,在此模式下,如果对数据进行更新操作,会有异常;
- CacheConcurrencyStrategy.READ_WRITE,读写模式在更新缓存的时候会把缓存里面的数据换成一个锁,其它事务如果去取相应的缓存数据,发现被锁了直接就去数据库查询;
- CacheConcurrencyStrategy.NONSTRICT_READ_WRITE,不严格的读写模式则不会对缓存数据加锁;
- CacheConcurrencyStrategy.TRANSACTIONAL,事务模式指缓存支持事务,当事务回滚时,缓存也能回滚,只支持JTA环境。
11.No-Annotation 字段:
If the property is of a single type, it is mapped as @Basic
Otherwise, if the type of the property is annotated as @Embeddable, it is mapped as @Embedded
Otherwise, if the type of the property is Serializable, it is mapped as @Basic in a column holding the object in its serialized version
Otherwise, if the type of the property is java.sql.Clob or java.sql.Blob, it is mapped as @Lob with the appropriate LobType