Hibernate 註解的用法以及說明(二)

來源:互聯網
上載者:User

標籤:des   blog   class   code   c   java   

註解映射必須滿足兩大條件:Hibernate3.2以上版本和JSEE 5。 
@Entity 類注釋,所有要持久化的類都要有
@Entity   
public class Org  implements java.io.Serializable {    
}   
@Id 主鍵       
@Id   
     @GeneratedValue   
     private String orgId;    
     private String orgName;   
@Column(name="...") 該屬性對應表中的欄位是什麼,沒有name表示一樣 
@Table 對象與表映射 
@UniqueConstraint 唯一約束 
@Version 方法和欄位級,樂觀鎖用法,返回數字和timestamp,數字為首選 
@Transient 暫態屬性,表示不需要處理 
@Basic 最基本的注釋。有兩個屬性:fetch是否消極式載入,optional是否允許null 
@Enumerated 枚舉類型 
@Temporal 日期轉換。預設轉換Timestamp 
@Lob 通常與@Basic同時使用,提高訪問速度。 
@Embeddable 類級,表可嵌入的 
@Embedded 方法欄位級,表被嵌入的對象和@Embeddable一起使用 
@AttributeOverrides 屬性重寫 
@AttributeOverride 屬性重寫的內容和@AttributeOverrides一起嵌套使用 
@SecondaryTables 多個表格映射 
@SecondaryTable 定義輔助表格映射和@SecondaryTables一起嵌套使用 
@GeneratedValue 標識符建置原則,預設Auto 
表與表關係映射 
@OneToOne:一對一映射。它包含五個屬性: 
targetEntity:關聯的目標類 
Cascade:持久化時的級聯操作,預設沒有 
fetch:擷取對象的方式,預設EAGER 
Optional:目標對象是否允許為null,預設允許 
mappedBy:定義雙向關聯中的從屬類。 
單向: 
    @JoinColumn:定義外鍵(主表會多一欄位,做外鍵) 
@OneToMany:一對多映射;@ManyToOne:多對一映射 
單向一對多: 
    @OneToMany(cascade=CascadeType.ALL) 
    @JoinColumn(name="book_oid")/**book:表;oid:book表的主鍵;無name會按此規則自動產生*/ 
單向多對一: 
    @ManyToOne(cascade=CascadeType.ALL) 
    @JoinColumn(name="author_oid") 
關聯表格一對多: 
    @OneToMany(cascade=CascadeType.ALL) 
    @JoinTable(joinColumn={@JoinColumn(name="BOOK_OBJECT_OID")},inverseJoinColumns={@JoinColumn(name="AUTHER_OBJECT_OID")}) 
雙向一對多或多對一: 
    不需要多一張表,只是使用mappedBy:使用在One一方,值為One方類名表示Many的從屬類。 
@Entity  
Java代碼 
@Entity   
public class Org  implements java.io.Serializable {    
   
   
    // Fields        
    @Id   
    @GeneratedValue   
     private String orgId;    
     private String orgName;    
     @OneToMany(mappedBy = "org")    
     private List<Department> departments;    
   
    // Constructors    
...    
    // Property accessors    
...    
}   

@Entity  public class Org  implements java.io.Serializable {        // Fields       @Id   @GeneratedValue       private String orgId;       private String orgName;       @OneToMany(mappedBy = "org")       private List<Department> departments;        // Constructors  ...      // Property accessors  ...  }


@Entity
public class Department implements java.io.Serializable {
    // Fields    
@Id
@GeneratedValue
     private String id;
     private String name;
     @ManyToOne(fetch=FetchType.EAGER)
     @JoinColumn(name="org_orgId")
     private Org org;
     @OneToMany(mappedBy = "department")
     private List<Employee> employees;
    // Constructors
    public List<Employee> getEmployees() {
return employees;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
public Org getOrg() {
return org;
}
public void setOrg(Org org) {
this.org = org;
}
/** default constructor */
             .
             .
             .
}
Java代碼 
@Entity   
public class Employee  implements java.io.Serializable {    
   
   
    // Fields        
    @Id   
    @GeneratedValue   
     private String employeeId;    
     private String employeeName;    
     private String passWord;    
     private Integer age;    
     private Integer sex;    
     @ManyToOne(fetch=FetchType.EAGER)    
     @JoinColumn(name="department_id")    
     private Department department;    
   
         
    public Department getDepartment() {    
        return department;    
     }    
   
    public void setDepartment(Department department) {    
        this.department = department;    
     }    
   
    /** default constructor */   
     ...    
    // Property accessors    
     ...    
}   

@Entity  public class Employee  implements java.io.Serializable {        // Fields       @Id   @GeneratedValue       private String employeeId;       private String employeeName;       private String passWord;       private Integer age;       private Integer sex;       @ManyToOne(fetch=FetchType.EAGER)       @JoinColumn(name="department_id")       private Department department;               public Department getDepartment() {    return department;   }     public void setDepartment(Department department) {    this.department = department;   }     /** default constructor */      ...      // Property accessors      ...  }


雙向多對多:@ManyToMany.單向多對多這裡不在贅述(沒有太多實際意義) 
這個比較簡單,看下代碼就明白了: 
@Entity
public class Book implements java.io.Serializable {
@Id
private int id;
private String name;
private float money;
@ManyToMany(cascade = CascadeType.ALL)
private List<Author> authors;
public List<Author> getAuthors() {
return authors;
}
public void setAuthors(List<Author> authors) {
this.authors = authors;
}
         ...
}
@Entity
public class Author implements java.io.Serializable {
@Id
private int id;
private String name;
private int age;
@ManyToMany(mappedBy="authors")
private List<Book> books;
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
         ...
}
基於註解的hibernate主鍵設定:@Id. 
那麼它的建置規則是什麼呢?是由@GeneratedValue來規定的。 
我們先來看看它是如何定義的: 
Java代碼 
@Target({METHOD,FIELD})    
    @Retention(RUNTIME)    
    public @interface GeneratedValue{    
         GenerationType strategy() default AUTO;    
         String generator() default "";    
     }   

@Target({METHOD,FIELD})   @Retention(RUNTIME)   public @interface GeneratedValue{    GenerationType strategy() default AUTO;    String generator() default "";   }


         
Java代碼 
public enum GenerationType{    
         TABLE,    
         SEQUENCE,    
         IDENTITY,    
         AUTO    
     }   

public enum GenerationType{    TABLE,    SEQUENCE,    IDENTITY,    AUTO   }


現在我們看到了,它提供了4種建置原則: 
TABLE:使用一個特定的資料庫表格來儲存標識符序列。 
SEQUENCE:產生序列化標識符。 
IDENTITY:標識符有資料庫自動產生(主要是自動成長型) 
AUTO:標識符產生工作由hibernate自動處理。實際項目開發不建議使用。 
注意:當主鍵為int,而資料庫中又不是自動成長型時,使用@GeneratedValue是無法正常工作的。 
我們也可以使用下面的方式來自己指定我們的主索引值: 
           
Java代碼 
@GeneratedValue(generator = "c-assigned")    
    @GenericGenerator(name = "c-assigned", strategy = "assigned")    
     private String employeeId;   

@GeneratedValue(generator = "c-assigned")   @GenericGenerator(name = "c-assigned", strategy = "assigned")       private String employeeId;


或者直接不要定義@GeneratedValue,只定義@Id效果也是一樣的。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.