摘要:時間年月日星期二說明本文部分內容均來自慕課網。文件如下在目錄下,創建文件指定映射文件的路徑注解映射實體類可選,對應數據庫中的一個表。
時間:2017年07月11日星期二
說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com
教學源碼:無
學習源碼:https://github.com/zccodere/s...
本章簡介
Hibernate注解簡介 JPA與Hibernate的關系 Hibernate注解分類 @Entity @Table @Embeddable schema與catalog
Hibernate注解簡介
使用注解的目的:為了簡化繁瑣的ORM映射文件(*.hbm)的配置
JPA與Hibernate的關系
什么是JPA 全稱Java Persistence API JPA注解是JavaEE的規范和標準 JPA和Hibernate的關系:
JPA是標準接口
Hibernate是實現,但是其功能是JPA的超集
Hibernate如何實現與JPA的關系 通過hibernate-annotation hibernate-entitymanager hibernate-core三個組件來實現 一般在實際開發中,優先考慮使用JPA注解
這樣更有利于程序的移植和擴展
Hibernate注解的分類
類級別注解 屬性級別注解 映射關系注解
類級別注解
@Entity:表示一個實體,一個實體對應數據庫一張表 @Table:配置表的屬性 @Embeddable:表示當前類是一個嵌入類1-2 準備工作
回顧hibernate.cfg.xml
創建一個名為hibernateca的maven項目,并添加相關依賴。POM文件如下
4.0.0 com.myimooc hibernateca 0.0.1-SNAPSHOT jar hibernateca http://maven.apache.org UTF-8 UTF-8 org.hibernate hibernate-core 4.2.4.Final mysql mysql-connector-java 5.1.38 junit junit 4.10 test org.apache.maven.plugins maven-compiler-plugin 1.8
在src/main/ resources目錄下,創建hibernate.cfg.xml文件
1-3 @Entity注解org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver root root true update
@Entity
@Entity:映射實體類 @Entity(name=”tableName”) name:可選,對應數據庫中的一個表。若表名與實體類名相同,則可以省略 注意:使用@Entity時必須指定實體類的主鍵屬性
代碼演示
1.編寫Students實體類
package com.myimooc.hibernateca.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * 學生實體類 * @author ZhangCheng on 2017-07-12 * */ //JPA注解 @Entity(name="t_students") public class Students { /** 學號 */ @Id private Integer sid; /** 姓名 */ private String sname; /** 性別 */ private String gender; /** 出生日期 */ private Date birthday; /** 專業 */ private String major; @Override public String toString() { return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", major=" + major + "]"; } public Students() { super(); } public Students(Integer sid, String sname, String gender, Date birthday, String major) { super(); this.sid = sid; this.sname = sname; this.gender = gender; this.birthday = birthday; this.major = major; this.address = address; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
2.配置映射
3.編寫StudentTest測試類
package com.myimooc.hibernateca.entity; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Test; /** * 單元測試類 * @author ZhangCheng on 2017-07-12 * */ public class StudentsTest { @Test public void schemaExportTest(){ // 創建hibernate配置對象 Configuration config = new Configuration().configure(); // 創建服務注冊對象 ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // 生成sessionFactory @SuppressWarnings("unused") SessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); SchemaExport export = new SchemaExport(config); export.create(true, true); } }1-4 @Table注解
@Table
@Table(name=””,catalog=””,schema=””) @Entity配置使用,只能標注在實體的class定義處,表示實體對應的數據庫表的信息 name:可選,映射表的名稱,默認表名和實體名稱一致,只有在不一致的情況下才需要指定表名 catalog:可選,表示目錄Catalog名稱,默認為Catalog(“”) schema:可選,表示模式Schema名稱,默認為Schema(“”)
schema與catalog示意圖
schema與catalog
從實現的角度來看,各種數據庫系統對Catalog和Schema的支持和實現方式千差萬別的
供應商的支持和實現
代碼演示,修改Student類如下
package com.myimooc.hibernateca.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * 學生實體類 * @author ZhangCheng on 2017-07-12 * */ //JPA注解 //@Entity(name="t_students") @Entity @Table(name="t_students",schema="hibernatemtm") public class Students { /** 學號 */ @Id private Integer sid; /** 姓名 */ private String sname; /** 性別 */ private String gender; /** 出生日期 */ private Date birthday; /** 專業 */ private String major; @Override public String toString() { return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", major=" + major + "]"; } public Students() { super(); } public Students(Integer sid, String sname, String gender, Date birthday, String major) { super(); this.sid = sid; this.sname = sname; this.gender = gender; this.birthday = birthday; this.major = major; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }1-5 @Embeddable注解
@Embeddable
@Embeddable表示一個非Entity類可以嵌入到另一個Entity類中作為屬性而存在
代碼演示
1.編寫Address類
package com.myimooc.hibernateca.entity; import javax.persistence.Embeddable; /** * 地址類(嵌入類) * @author ZhangCheng on 2017-07-12 * */ // 表示是一個嵌入類,這個類的對象在另一個實體類中充當屬性 @Embeddable public class Address { /** 郵編 */ private String postCode; /** 地址 */ private String address; /** 聯系電話 */ private String phone; @Override public String toString() { return "Address [postCode=" + postCode + ", address=" + address + ", phone=" + phone + "]"; } public Address() { } public Address(String postCode, String address, String phone) { this.postCode = postCode; this.address = address; this.phone = phone; } public String getPostCode() { return postCode; } public void setPostCode(String postCode) { this.postCode = postCode; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
2.修改Student類如下
package com.myimooc.hibernateca.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * 學生實體類 * @author ZhangCheng on 2017-07-12 * */ //JPA注解 //@Entity(name="t_students") @Entity @Table(name="t_students",schema="hibernatemtm") public class Students { /** 學號 */ @Id private Integer sid; /** 姓名 */ private String sname; /** 性別 */ private String gender; /** 出生日期 */ private Date birthday; /** 專業 */ private String major; /** 地址 */ private Address address; @Override public String toString() { return "Students [sid=" + sid + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", major=" + major + "]"; } public Students() { super(); } public Students(Integer sid, String sname, String gender, Date birthday, String major,Address address) { super(); this.sid = sid; this.sname = sname; this.gender = gender; this.birthday = birthday; this.major = major; this.address = address; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }第二章:屬性級別注解 2-1 本章簡介
Hibernate屬性級別注解
添加方式:寫在屬性字段方面 或 寫在屬性的get訪問器的上面 @Id -@SequenceGenerator @GeneratedValue @Column @Embedded @EmbeddedId -@Lob -@Version -@Basic @Transient2-2 @Id注解
@Id
@Id:必須,定義了映射到數據庫表的主鍵的屬性, 一個實體類可以有一個或者多個屬性被映射為主鍵, 可置于主鍵屬性或者get方法前 注意:如果有多個屬性定義為主鍵屬性, 該實體類必須實現serializable接口
拷貝hibernateca項目,重命名為hibernateaa,POM與Hibernate配置文件均相同
2-3 @GeneratedValue注解(一)@GeneratedValue
@GeneratedValue(strategy=GenerationType,generator=””) 可選,用戶定義主鍵生成策略 strategy表示主鍵生成策略,取值有 GenerationType.AUTO:根據底層數據庫自動選擇(默認) GenerationType.INDENTITY:根據數據庫的Identity字段生成 GenerationType.SEQUENCE:使用Sequence來決定主鍵的取值 GenerationType.TABLE:使用指定表來決定主鍵取值,結合@TableGenerator使用
使用示例
2-4 @GeneratedValue注解(二)代碼演示
1.修改Students類
package com.myimooc.hibernateaa.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.GenericGenerator; /** * 學生實體類 * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") @Entity @Table(name="t_students",schema="hibernatemtm") public class Students { /** 學號 */ /* 方式一:使用自動生成主鍵 @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer sid; */ /* 方式二:使用手工賦值方式生成主鍵 @Id @GeneratedValue(generator="sid") @GenericGenerator(name="sid",strategy="assigned")// @Column(length=8) private String sid; */ /* 方式三:使用復合主鍵 */ @EmbeddedId private StudentsPK pk; /** 姓名 */ private String sname; /** 性別 */ private String gender; /** 出生日期 */ private Date birthday; /** 專業 */ private String major; /** 薪水 */ @Transient // 表示該屬性不會被ORM映射到表里的字段 private double salary; /** 地址 */ @Embedded private Address address; @Override public String toString() { return "Students [pk=" + pk + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", major=" + major + ", salary=" + salary + ", address=" + address + "]"; } public Students() { super(); } public Students(StudentsPK pk, String sname, String gender, Date birthday, String major,Address address) { super(); this.pk = pk; this.sname = sname; this.gender = gender; this.birthday = birthday; this.major = major; this.address = address; } public Students(StudentsPK pk, String sname, String gender, Date birthday, String major, double salary, Address address) { super(); this.pk = pk; this.sname = sname; this.gender = gender; this.birthday = birthday; this.major = major; this.salary = salary; this.address = address; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public StudentsPK getPk() { return pk; } public void setPk(StudentsPK pk) { this.pk = pk; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }2-5 @GeneratedValue注解(三)
代碼演示
1.修改StudentsTest類
package com.myimooc.hibernateaa.entity; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Before; import org.junit.Test; /** * 單元測試類 * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") public class StudentsTest { private SessionFactory sessionFactory = null; @Before public void schemaExportTest(){ // 創建hibernate配置對象 Configuration config = new Configuration().configure(); // 創建服務注冊對象 ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // 生成sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); // SchemaExport export = new SchemaExport(config); // export.create(true, true); } @Test public void addStudents(){ // 創建會話 Session session = sessionFactory.getCurrentSession(); // 創建事務 Transaction tx = session.beginTransaction(); // 創建一個學生對象 Address address = new Address("700005","湖北武當山","18991167346"); // Students s = new Students("S0000002","張三豐","男",new Date(),"太極拳",address); // // session.save(s); tx.commit(); } @Test public void addStudentsByPk(){ // 創建會話 Session session = sessionFactory.getCurrentSession(); // 創建事務 Transaction tx = session.beginTransaction(); // 創建一個學生對象 Address address = new Address("700005","湖北武當山","18991167346"); // 創建學生主鍵對象 StudentsPK pk = new StudentsPK(); pk.setId("123456789012345678"); pk.setSid("1235241231"); Students s = new Students(pk,"張三豐","男",new Date(),"太極拳",address); session.save(s); tx.commit(); } }2-6 @Column注解
@Column
@Column:可將屬性映射到列,使用該注解來覆蓋默認值 @Column描述了數據庫表中該字段的詳細定義 這對于根據JPA注解生成數據庫表結構的工具非常有作用
常用屬性
name:可選,表示數據庫表中該字段的名稱,默認與屬性名稱一致 nullable:可選,表示該字段是否允許為null,默認為true unique:可選,表示該字段是否是唯一標識,默認為false length:可選,表示該字段的大小,僅對String類型的字段有效,默認為255 (如果是主鍵不能使用默認值) insertable:可選,表示在ORM框架執行插入操作時,該字段是否應出現INSERT語句中,默認為true updateable:可選,表示在ORM框架執行更新操作時,該字段是否應該出現在UPDATE語句中,默認為true 對于一經創建就不可以更改的字段,該屬性非常有用,如對于birthday字段2-7 @Embedded注解
@Embedded
@Embedded是注釋屬性的,表示該屬性的類是嵌入類 注意:同時嵌入類也必須標注@Embeddable注解2-8 @EmbeddedId注解
@EmbeddedId
@EmbeddedId使用嵌入式主鍵類實現復合主鍵 注意:嵌入式主鍵類 必須實現Serializable接口 必須有默認的public無參數的構造方法 必須覆蓋equals和hashCode方法
代碼演示
1.編寫StudentsPK類
package com.myimooc.hibernateaa.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; /** * 學生主鍵類 * @author ZhangCheng on 2017-07-12 * */ @Embeddable public class StudentsPK implements Serializable{ private static final long serialVersionUID = 1L; /** 省份證號碼 */ @Column(length=18) private String id; /** 學號 */ @Column(length=10) private String sid; public StudentsPK() { } @Override public String toString() { return "StudentsPK [id=" + id + ", sid=" + sid + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((sid == null) ? 0 : sid.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; StudentsPK other = (StudentsPK) obj; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (sid == null) { if (other.sid != null) return false; } else if (!sid.equals(other.sid)) return false; return true; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getSid() { return sid; } public void setSid(String sid) { this.sid = sid; } }
2.修改Students類
package com.myimooc.hibernateaa.entity; import java.util.Date; import javax.persistence.Column; import javax.persistence.Embedded; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.GenericGenerator; /** * 學生實體類 * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") @Entity @Table(name="t_students",schema="hibernatemtm") public class Students { /** 學號 */ /* 方式一:使用自動生成主鍵 @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer sid; */ /* 方式二:使用手工賦值方式生成主鍵 @Id @GeneratedValue(generator="sid") @GenericGenerator(name="sid",strategy="assigned")// @Column(length=8) private String sid; */ /* 方式三:使用復合主鍵 */ @EmbeddedId private StudentsPK pk; /** 姓名 */ private String sname; /** 性別 */ private String gender; /** 出生日期 */ private Date birthday; /** 專業 */ private String major; /** 薪水 */ @Transient // 表示該屬性不會被ORM映射到表里的字段 private double salary; /** 地址 */ @Embedded private Address address; @Override public String toString() { return "Students [pk=" + pk + ", sname=" + sname + ", gender=" + gender + ", birthday=" + birthday + ", major=" + major + ", salary=" + salary + ", address=" + address + "]"; } public Students() { super(); } public Students(StudentsPK pk, String sname, String gender, Date birthday, String major,Address address) { super(); this.pk = pk; this.sname = sname; this.gender = gender; this.birthday = birthday; this.major = major; this.address = address; } public Students(StudentsPK pk, String sname, String gender, Date birthday, String major, double salary, Address address) { super(); this.pk = pk; this.sname = sname; this.gender = gender; this.birthday = birthday; this.major = major; this.salary = salary; this.address = address; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public StudentsPK getPk() { return pk; } public void setPk(StudentsPK pk) { this.pk = pk; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
3.修改StudentsTest類
package com.myimooc.hibernateaa.entity; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Before; import org.junit.Test; /** * 單元測試類 * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") public class StudentsTest { private SessionFactory sessionFactory = null; @Before public void schemaExportTest(){ // 創建hibernate配置對象 Configuration config = new Configuration().configure(); // 創建服務注冊對象 ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // 生成sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); // SchemaExport export = new SchemaExport(config); // export.create(true, true); } @Test public void addStudents(){ // 創建會話 Session session = sessionFactory.getCurrentSession(); // 創建事務 Transaction tx = session.beginTransaction(); // 創建一個學生對象 Address address = new Address("700005","湖北武當山","18991167346"); // Students s = new Students("S0000002","張三豐","男",new Date(),"太極拳",address); // // session.save(s); tx.commit(); } @Test public void addStudentsByPk(){ // 創建會話 Session session = sessionFactory.getCurrentSession(); // 創建事務 Transaction tx = session.beginTransaction(); // 創建一個學生對象 Address address = new Address("700005","湖北武當山","18991167346"); // 創建學生主鍵對象 StudentsPK pk = new StudentsPK(); pk.setId("123456789012345678"); pk.setSid("1235241231"); Students s = new Students(pk,"張三豐","男",new Date(),"太極拳",address); session.save(s); tx.commit(); } }2-9 @Transient注解
@Transient
可選,表示該屬性并非一個到數據庫表的字段的映射,ORM框架將忽略該屬性,如果一個屬性并非數據庫表的字段映射,就務必將其表示為@Transient,否則ORM框架默認其注解為@Basic第三章:關聯映射注解 3-1 本章簡介
簡介
一對一單向外鍵關聯 一對一雙向外鍵關聯 一對一單向外鍵聯合主鍵 多對一單向外鍵關聯 一對多單向外鍵關聯 一對多雙向外鍵關聯 多對多單向外鍵關聯 多對多雙向外鍵關聯3-2 實體之間的關系
實體之間的映射關系
一對一:一個公民對應一個身份證號碼 一對多(多對一):一個公民有多個銀行賬號 多對多:一個學生有多個老師,一個老師有多個學生3-3 一對一單向外鍵關聯(一)
一對一單向外鍵
@OneToOne(cascade=CascadeType.ALL) @JoinColumn(name=”pid”,unique=true) 注意:保存時應該先保存外鍵對象,再保存主表對象
拷貝hibernateca項目,重命名為hibernatera,POM與Hibernate配置文件均相同
代碼演示
1.編寫Students類
package com.myimooc.hibernatera.onetoonefk; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; /** * 一對一單向外鍵關聯 * 學生實體類 * @author ZhangCheng on 2017-07-12 * */ @Entity public class Students { /** 學號 */ @Id @GeneratedValue private Integer sid; /** 身份證類 */ @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="pid",unique=true) private IdCard card; /** 性別 */ private String gender; /** 出生日期 */ private Date birthday; /** 專業 */ private String major; @Override public String toString() { return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday + ", major=" + major + "]"; } public Students() { } public Students(IdCard card, String gender, Date birthday, String major) { super(); this.card = card; this.gender = gender; this.birthday = birthday; this.major = major; } public Students(IdCard card,Integer sid, String gender, Date birthday, String major) { this.card = card; this.sid = sid; this.gender = gender; this.birthday = birthday; this.major = major; } public IdCard getCard() { return card; } public void setCard(IdCard card) { this.card = card; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
2.編寫IdCard類
package com.myimooc.hibernatera.onetoonefk; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; /** * 一對一單向外鍵關聯 * 身份證實體類 * @author ZhangCheng on 2017-07-12 * */ @Entity public class IdCard { @Id @GeneratedValue(generator = "pid") @GenericGenerator(name="pid",strategy="assigned") @Column(length=18) /** 身份證號碼 */ private String pid; /** 學生的姓名 */ private String sname; public IdCard() { } public IdCard(String pid, String sname) { this.pid = pid; this.sname = sname; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } }
3.修改Hibernate配置文件
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver root root true update thread
4.編寫StudentsTest類
package com.myimooc.hibernatera.onetoonefk; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Before; import org.junit.Test; /** * 一對一雙單外鍵關聯 * 單元測試類 * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") public class StudentsTest { private SessionFactory sessionFactory = null; @Before public void schemaExportTest(){ // 創建hibernate配置對象 Configuration config = new Configuration().configure(); // 創建服務注冊對象 ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // 生成sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); // SchemaExport export = new SchemaExport(config); // // export.create(true, true); } }3-4 一對一單向外鍵關聯(二)
代碼演示
1.修改StudentsTest類
package com.myimooc.hibernatera.onetoonefk; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Before; import org.junit.Test; /** * 一對一雙單外鍵關聯 * 單元測試類 * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") public class StudentsTest { private SessionFactory sessionFactory = null; @Before public void schemaExportTest(){ // 創建hibernate配置對象 Configuration config = new Configuration().configure(); // 創建服務注冊對象 ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // 生成sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); // SchemaExport export = new SchemaExport(config); // // export.create(true, true); } /** * 一對一單向外鍵關聯保存測試 */ @Test public void addStudents(){ Session session = sessionFactory.getCurrentSession(); // 生成一個身份證對象 IdCard card = new IdCard("123456789012345678","張無忌"); Transaction tx = session.beginTransaction(); // 生成學生對象 Students s = new Students(card, "男", new Date(), "太極拳"); // 先保存身份證類的對象 session.save(card); session.save(s); tx.commit(); } }3-5 一對一雙向外鍵關聯
一對一雙向外鍵
主控方的配置同一對一單向外鍵關聯相同 @OneToOne(mappedBy=”card”)//被控方 雙向關聯,必須設置mappedBy屬性。因為雙向關聯只能交給一方去控制 不可能在雙方都設置外鍵保存關聯關系,否則雙方都無法保存
代碼演示
1.編寫Students類
package com.myimooc.hibernatera.onetoonebfk; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; /** * 一對一雙向外鍵關聯 * 學生實體類 * @author ZhangCheng on 2017-07-12 * */ @Entity public class Students { /** 學號 */ @Id @GeneratedValue private Integer sid; /** 身份證類 */ @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="pid",unique=true) private IdCard card; /** 性別 */ private String gender; /** 出生日期 */ private Date birthday; /** 專業 */ private String major; @Override public String toString() { return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday + ", major=" + major + "]"; } public Students() { } public Students(IdCard card, String gender, Date birthday, String major) { super(); this.card = card; this.gender = gender; this.birthday = birthday; this.major = major; } public Students(IdCard card,Integer sid, String gender, Date birthday, String major) { this.card = card; this.sid = sid; this.gender = gender; this.birthday = birthday; this.major = major; } public IdCard getCard() { return card; } public void setCard(IdCard card) { this.card = card; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
2.編寫IdCard類
package com.myimooc.hibernatera.onetoonebfk; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import org.hibernate.annotations.GenericGenerator; /** * 一對一雙向外鍵關聯 * 身份證實體類 * @author ZhangCheng on 2017-07-12 * */ @Entity public class IdCard { @Id @GeneratedValue(generator = "pid") @GenericGenerator(name="pid",strategy="assigned") @Column(length=18) /** 身份證號碼 */ private String pid; /** 學生的姓名 */ private String sname; /** 學生的引用 */ @OneToOne(mappedBy="card") private Students stu; public Students getStu() { return stu; } public void setStu(Students stu) { this.stu = stu; } public IdCard() { } public IdCard(String pid, String sname) { this.pid = pid; this.sname = sname; } public String getPid() { return pid; } public void setPid(String pid) { this.pid = pid; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } }
3.修改hibernate配置文件
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver root root true update thread
4.編寫StudentsTest類
package com.myimooc.hibernatera.onetoonebfk; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Before; import org.junit.Test; /** * 一對一雙向外鍵關聯 * 單元測試類 * @author ZhangCheng on 2017-07-12 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // 創建hibernate配置對象 Configuration config = new Configuration().configure(); // 創建服務注冊對象 ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // 生成sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); SchemaExport export = new SchemaExport(config); export.create(true, true); } /** * 一對一雙向外鍵關聯保存測試 */ @Test public void addStudents(){ Session session = sessionFactory.getCurrentSession(); // 生成一個身份證對象 IdCard card = new IdCard("123456789012345678","張無忌"); Transaction tx = session.beginTransaction(); // 生成學生對象 Students s = new Students(card, "男", new Date(), "太極拳"); // 先保存身份證類的對象 session.save(card); session.save(s); tx.commit(); } }3-6 一對一單向外鍵聯合主鍵
一對一雙向外鍵聯合主鍵
創建主鍵類 主鍵類必須實現serializable接口,重寫hashCode()和equals()方法 主鍵類:@Embeddable 實體類:@EmbeddedId3-7 多對一單向外鍵關聯(一)
多對一單向外鍵
多方持有一方的引用,比如:多個學生對應一個班級(多對一) 在多方添加以下注解 @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER) @JoinColumn(name=”cid”,referencedColumnName=”CID”)
代碼演示
1.編寫Students類
package com.myimooc.hibernatera.manytoonefk; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; /** * 多對一單向外鍵關聯 * 學生實體類(多方) * @author ZhangCheng on 2017-07-13 * */ @Entity public class Students { /** 學號 */ @Id @GeneratedValue private Integer sid; /** 學生姓名 */ private String sname; /** 性別 */ private String gender; /** 出生日期 */ private Date birthday; /** 專業 */ private String major; // 多方持有一方的引用 @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)// 配置級聯關系和抓取策略 @JoinColumn(name="cid",referencedColumnName="CID") // 指定外鍵 private ClassRoom classRoom; @Override public String toString() { return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday + ", major=" + major + "]"; } public Students() { } public Students(String sname, String gender, Date birthday, String major) { super(); this.sname = sname; this.gender = gender; this.birthday = birthday; this.major = major; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public ClassRoom getClassRoom() { return classRoom; } public void setClassRoom(ClassRoom classRoom) { this.classRoom = classRoom; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
2.編寫ClassRoom類
package com.myimooc.hibernatera.manytoonefk; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import org.hibernate.annotations.GenericGenerator; /** * 多對一單向外鍵關聯 * 班級實體類(一方) * @author ZhangCheng on 2017-07-13 * */ @Entity public class ClassRoom { /** 班級編號 */ @Id @GeneratedValue(generator="cid") @GenericGenerator(name="cid",strategy="assigned") @Column(length=4) private String cid; /** 班級名字 */ private String cname; public ClassRoom() { } public ClassRoom(String cid, String cname) { this.cid = cid; this.cname = cname; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } @Override public String toString() { return "ClassRoom [cid=" + cid + ", cname=" + cname + "]"; } }
3.修改hibernate配置文件
org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver root root true update thread
4.編寫StudentsTest類
package com.myimooc.hibernatera.manytoonefk; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Before; import org.junit.Test; /** * 多對一單向外鍵關聯 * 單元測試類 * @author ZhangCheng on 2017-07-13 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // 創建hibernate配置對象 Configuration config = new Configuration().configure(); // 創建服務注冊對象 ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // 生成sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); SchemaExport export = new SchemaExport(config); export.create(true, true); } }3-8 多對一單向外鍵關聯(二)
代碼演示
1.修改StudentsTest類
package com.myimooc.hibernatera.manytoonefk; import java.util.Date; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Before; import org.junit.Test; /** * 多對一單向外鍵關聯 * 單元測試類 * @author ZhangCheng on 2017-07-13 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // 創建hibernate配置對象 Configuration config = new Configuration().configure(); // 創建服務注冊對象 ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // 生成sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); SchemaExport export = new SchemaExport(config); export.create(true, true); } @Test public void addStudents(){ Session session = sessionFactory.getCurrentSession(); Transaction tx = session.beginTransaction(); // 創建班級對象 ClassRoom c1 = new ClassRoom("C001","軟件工程"); ClassRoom c2 = new ClassRoom("C002","網絡工程"); // 創建學生對象 Students s1 = new Students("張三","男", new Date(), "計算機"); Students s2 = new Students("李四","男", new Date(), "計算機"); Students s3 = new Students("王五","女", new Date(), "計算機"); Students s4 = new Students("趙六","女", new Date(), "計算機"); s1.setClassRoom(c1); s2.setClassRoom(c1); s3.setClassRoom(c2); s4.setClassRoom(c2); // 先保存班級 session.save(c1); session.save(c2); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); } }3-9 一對多單向外鍵關聯
一對多單向外鍵
一方持有多方的集合,一個班級有多個學生(一對多) 在一方添加以下注解 @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY) @JoinColumn(name=”cid”)
抓取策略總結
多對一時候 多方設置EAGER:表示積極加載 一方設置LAZY:表示懶加載
代碼演示
1.編寫Students類
package com.myimooc.hibernatera.onetomanyfk; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * 一對多單向外鍵關聯 * 學生實體類(多方) * @author ZhangCheng on 2017-07-13 * */ @Entity public class Students { /** 學號 */ @Id @GeneratedValue private Integer sid; /** 學生姓名 */ private String sname; /** 性別 */ private String gender; /** 出生日期 */ private Date birthday; /** 專業 */ private String major; @Override public String toString() { return "Students [sid=" + sid + ", sname=" + ", gender=" + gender + ", birthday=" + birthday + ", major=" + major + "]"; } public Students() { } public Students(String sname, String gender, Date birthday, String major) { super(); this.sname = sname; this.gender = gender; this.birthday = birthday; this.major = major; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public Integer getSid() { return sid; } public void setSid(Integer sid) { this.sid = sid; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getMajor() { return major; } public void setMajor(String major) { this.major = major; } }
2.編寫ClassRoom類
package com.myimooc.hibernatera.onetomanyfk; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import org.hibernate.annotations.GenericGenerator; /** * 一對多單向外鍵關聯 * 班級實體類(一方) * @author ZhangCheng on 2017-07-13 * */ @Entity public class ClassRoom { /** 班級編號 */ @Id @GeneratedValue(generator="cid") @GenericGenerator(name="cid",strategy="assigned") @Column(length=4) private String cid; /** 班級名字 */ private String cname; // 一方持有多方的集合 @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY) @JoinColumn(name="cid") private Setstus; public ClassRoom() { } public ClassRoom(String cid, String cname) { this.cid = cid; this.cname = cname; } public Set getStus() { return stus; } public void setStus(Set stus) { this.stus = stus; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getCname() { return cname; } public void setCname(String cname) { this.cname = cname; } @Override public String toString() { return "ClassRoom [cid=" + cid + ", cname=" + cname + "]"; } }
3.修改hibernate配置文件
同上
4.編寫StudentsTest類
package com.myimooc.hibernatera.onetomanyfk; import java.util.Date; import java.util.HashSet; import java.util.Set; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; import org.hibernate.service.ServiceRegistryBuilder; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.Before; import org.junit.Test; /** * 一對多單向外鍵關聯 * 單元測試類 * @author ZhangCheng on 2017-07-13 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // 創建hibernate配置對象 Configuration config = new Configuration().configure(); /
文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。
轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/67370.html
摘要:小時學會學習總結時間年月日星期六說明本文部分內容均來自慕課網。慕課網教學示例源碼暫無。數據庫操作下第六章事務管理事務管理只有查詢的時候不加事務,其它任何操作都要加事務。第七章課程回顧課程回顧總結介紹安裝配置的使用數據庫操作 《2小時學會SpringBoot》學習總結 時間:2017年2月18日星期六說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學示...
摘要:入門篇學習總結時間年月日星期三說明本文部分內容均來自慕課網。主要的功能是日志記錄,性能統計,安全控制,事務處理,異常處理等等。 《Spring入門篇》學習總結 時間:2017年1月18日星期三說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學示例源碼:https://github.com/zccodere/s...個人學習源碼:https://git...
摘要:時間年月日星期二說明本文部分內容均來自慕課網。項目一個項目代表一個正在構建的組件比如一個文件,當構建啟動后,會基于實例化一個類,并且能夠通過變量使其隱式可用。任務動作定義了一個最小的工作單元。 時間:2017年05月16日星期二說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學示例源碼:無個人學習源碼:https://github.com/zccod...
摘要:時間年月日星期二說明本文部分內容均來自慕課網。返回對象不同返回持久化實體類對象返回代理對象。與緩存的關系不同只緩存,但不使用緩存查詢緩存除外會使用緩存。 時間:2017年07月11日星期二說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學源碼:無學習源碼:無 第一章:概述 1-1 概述 課程內容 了解緩存 掌握Hibernate一級緩存的使用 掌握H...
時間:2017年07月11日星期二說明:本文部分內容均來自慕課網。@慕課網:http://www.imooc.com教學源碼:無學習源碼:https://github.com/zccodere/s... 第一章:應用場景 1-1 多對多的應用場景 案例分析:企業項目開發過程中 一個項目可由多個員工參與開發 一個員工可同時參與開發多個項目 示意圖 showImg(https://segmentfau...
閱讀 1123·2023-04-26 00:12
閱讀 3249·2021-11-17 09:33
閱讀 1061·2021-09-04 16:45
閱讀 1186·2021-09-02 15:40
閱讀 2145·2019-08-30 15:56
閱讀 2950·2019-08-30 15:53
閱讀 3548·2019-08-30 11:23
閱讀 1932·2019-08-29 13:54