(自己的筆記)以一個Admin類作為說明1.首先@Entity 註解將一個類聲明為實體Bean@Table 映射數句庫表2.創建表的主鍵@Id用來註冊主屬性@GeneratedValue來說明主鍵的自增長3.創建列@Column 註解將屬性映射到列@Column( name="columnName"... ...
(自己的筆記)
以一個Admin類作為說明
1.首先
@Entity 註解將一個類聲明為實體Bean
@Table 映射數句庫表
2.創建表的主鍵
@Id用來註冊主屬性
@GeneratedValue來說明主鍵的自增長
3.創建列
@Column 註解將屬性映射到列 @Column( name="columnName"; (1) 列名 boolean unique() default false; (2) 是否在該列上設置唯一約束 boolean nullable() default true; (3) 列可空? boolean insertable() default true; (4) 該列是否作為生成 insert語句的一個列 boolean updatable() default true; (5) 該列是否作為生成 update語句的一個列 String columnDefinition() default""; (6) 預設值 String table() default "";(7) 定義對應的表(deault 是主表) int length() default 255; (8) 列長度 int precision() default 0; // decimalprecision (9) decimal精度 int scale() default 0; // decimal scale (10) decimal長度
}
4.註解完成之後,通過xml連接到資料庫
5.最後,通過Session測試註解
//插入語句 public void insertData() { Session session=HibernateUtils.getOpenSession(); Transaction ts=session.beginTransaction(); try { session.save(new Admin("admin","1234")); } catch(Exception e){ System.out.println("error"); } ts.commit(); session.close(); }
package main.java; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; @Entity //實體 @Table(name="admin") //創建表 public class Admin { private int adminID; //管理員ID private String adminName; //管理員賬號 private String adminPassword; //管理員密碼 @Id //主鍵 @GeneratedValue //自增長 public int getAdminID() { return adminID; } public void setAdminID(int adminID) { this.adminID = adminID; } @Column(name="adminName",length=20,unique=true) public String getAdminName() { return adminName; } public void setAdminName(String adminName) { this.adminName = adminName; } @Column(name="adminPassword",length=20,unique=false) public String getAdminPassword() { return adminPassword; } public void setAdminPassword(String adminPassword) { this.adminPassword = adminPassword; } public Admin(int adminID, String adminName, String adminPassword) { super(); this.adminID = adminID; this.adminName = adminName; this.adminPassword = adminPassword; } public Admin(String adminName, String adminPassword) { super(); this.adminName = adminName; this.adminPassword = adminPassword; } public Admin(int adminID) { super(); this.adminID = adminID; } @Override public String toString() { return "Admin [adminID=" + adminID + ", adminName=" + adminName + ", adminPassword=" + adminPassword + "]"; } }