上一篇说到了如何对Hibernate进行设置和初始化,加下来就是如何使用Annotations映射了。
首先介绍EJB3的映射Annotations位于javax.persistence.*包内。先看看如何声明一个Entity Bean。
@Entity
public class Flight implements Serializable {
Long id;
@Id
public Long getId() { return id; }
public setId(Long id) { this.id = id; }
}
一个完整的例子参考 Flight.java
@entity声明了这个类是一个Entity Bean(同时这个类是个普通的POJO)
@Id声明了这个类的标识符,其它映射声明都隐含了
@entity允许你定义一个Entity Bean是否可以通过getters/setters方法访问,或者说是否可以直接访问他的成员变量。
@Entity(access = AccessType.PROPERTY)
or
@Entity(access = AccessType.FIELD)
下面看看如何定义与数据库表的映射@Entity(access=AccessType.FIELD)
@Table(name="tbl_sky")
public class Sky implements Serializable {
...
完整的例子看 Sky.java
你可以定义乐观锁机制使用@Version
@Entity()
public class Flight implements Serializable {
...
@Version
@Column(name="OPTLOCK")
public Integer getVersion() { ... }
}
映射简单属性@Transient
String getLengthInMeter() { ... }
String getName() {... } // persistent property
@Basic
int getLength() { ... } // persistent property
@Basic(fetch = FetchType.LAZY)
String getDetailedComment() { ... }
@Transient标示的lengthInMeter属性将被entity manager忽略。
detailedComment将实行懒加载。
凡标识@Serialized的属性将被序列化。@Lob标识了存储对象可能是个CLOB或者BLOB。
@Serialized
public Country getCountry() {
...
}
@Lob(type=LobType.CLOB)
public String getFullText() {
return fullText;
}
@Lob(type = LobType.BLOB)
public byte[] getFullCode() {
return fullCode;
}
定义列属性
@Entity()
public class Flight implements Serializable {
...
@Column(updatable = false, name = "flight_name", nullable = false, length=50)
public String getName() { ... }
内嵌对象(组件)
@Entity(access = AccessType.FIELD)
public class Person implements Serializable {
// Persistent component using defaults
Address homeAddress;
@Embedded({
@AttributeOverride(name="iso2", column = @Column(name="bornIso2") ),
@AttributeOverride(name="name", column = @Column(name="bornCountryName") )
})
Country bornIn;
...
}
@Embeddable(access = AccessType.FIELD)
public class Address implements Serializable {
String city;
Country nationality;
}
@Embeddable
public class Country implements Serializable {
private String iso2;
private String name;
public String getIso2() { return iso2; }
public void setIso2(String iso2) { this.iso2 = iso2; }
@Column(name="countryName")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
...
}
映射标识符
@Id(generate=GeneratorType.SEQUENCE, generator="SEQ_STORE")
public Integer getId() { ... }
@Id(generate=GeneratorType.IDENTITY)
public Integer getId() { ... }
自定义的主键生成策略
@javax.persistence.GeneratedIdTable(
name="GEN_TABLE",
table = @Table(name="GENERATOR_TABLE"),
pkColumnName = "key",
valueColumnName = "hi"
)
@javax.persistence.TableGenerator(
name="EMP_GEN",
tableName="GEN_TABLE",
pkColumnValue="EMP",
allocationSize=20
)
@javax.persistence.SequenceGenerator(
name="SEQ_GEN",
sequenceName="my_sequence"
)
package org.hibernate.test.metadata;
(未完待续)