- 相關(guān)軟件
>EJB3 and Hibernate3 Annotations 學(xué)習(xí)筆記(二) 創(chuàng)建者:webmaster 更新時間:2005-05-16 22:00
上一篇說到了如何對Hibernate進行設(shè)置和初始化,加下來就是如何使用Annotations映射了。
首先介紹EJB3的映射
Annotations位于javax.persistence.*包內(nèi)。先看看如何聲明一個Entity Bean。
@Entitypublic 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)
下面看看如何定義與數(shù)據(jù)庫表的映射
@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() { ... }}映射簡單屬性@TransientString getLengthInMeter() { ... }String getName() {... } // persistent property@Basicint 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() { ... }
內(nèi)嵌對象(組件)
@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;}
@Embeddablepublic 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;(未完待續(xù))相關(guān)文章
本頁查看次數(shù):