時間:2017年07月11日星期二
說明:本文部份內容均來自慕課網。@慕課網:http://www.imooc.com
教學源碼:無
學習源碼:https://github.com/zccodere/s...java
本章簡介mysql
Hibernate註解簡介 JPA與Hibernate的關係 Hibernate註解分類 @Entity @Table @Embeddable schema與catalog
Hibernate註解簡介git
使用註解的目的:爲了簡化繁瑣的ORM映射文件(*.hbm)的配置
JPA與Hibernate的關係github
什麼是JPA 全稱Java Persistence API JPA註解是JavaEE的規範和標準 JPA和Hibernate的關係:
JPA是標準接口
Hibernate是實現,可是其功能是JPA的超集sql
Hibernate如何實現與JPA的關係 經過hibernate-annotation hibernate-entitymanager hibernate-core三個組件來實現 通常在實際開發中,優先考慮使用JPA註解
這樣更有利於程序的移植和擴展
Hibernate註解的分類數據庫
類級別註解 屬性級別註解 映射關係註解
類級別註解apache
@Entity:表示一個實體,一個實體對應數據庫一張表 @Table:配置表的屬性 @Embeddable:表示當前類是一個嵌入類
回顧hibernate.cfg.xml網絡
建立一個名爲hibernateca的maven項目,並添加相關依賴。POM文件以下session
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.myimooc</groupId> <artifactId>hibernateca</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>hibernateca</name> <url>http://maven.apache.org</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> </properties> <dependencies> <!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-core --> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>4.2.4.Final</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </build> </project>
在src/main/ resources目錄下,建立hibernate.cfg.xml文件app
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.url"> <![CDATA[ jdbc:mysql://localhost:3306/hibernatemtm?useUnicode=true&characterEncoding=utf8 ]]> </property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- 指定映射文件的路徑 --> <mapping class="com.myimooc.hibernateca.entity.Students"/> </session-factory> </hibernate-configuration>
@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.配置映射
<!-- 指定映射文件的路徑 --> <mapping class="com.myimooc.hibernateca.entity.Students"/>
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); } }
@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; } }
@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; } }
Hibernate屬性級別註解
添加方式:寫在屬性字段方面 或 寫在屬性的get訪問器的上面 @Id -@SequenceGenerator @GeneratedValue @Column @Embedded @EmbeddedId -@Lob -@Version -@Basic @Transient
@Id
@Id:必須,定義了映射到數據庫表的主鍵的屬性, 一個實體類能夠有一個或者多個屬性被映射爲主鍵, 可置於主鍵屬性或者get方法前 注意:若是有多個屬性定義爲主鍵屬性, 該實體類必須實現serializable接口
拷貝hibernateca項目,重命名爲hibernateaa,POM與Hibernate配置文件均相同
@GeneratedValue
@GeneratedValue(strategy=GenerationType,generator=」」) 可選,用戶定義主鍵生成策略 strategy表示主鍵生成策略,取值有 GenerationType.AUTO:根據底層數據庫自動選擇(默認) GenerationType.INDENTITY:根據數據庫的Identity字段生成 GenerationType.SEQUENCE:使用Sequence來決定主鍵的取值 GenerationType.TABLE:使用指定表來決定主鍵取值,結合@TableGenerator使用
使用示例
代碼演示
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; } }
代碼演示
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(); } }
@Column
@Column:可將屬性映射到列,使用該註解來覆蓋默認值 @Column描述了數據庫表中該字段的詳細定義 這對於根據JPA註解生成數據庫表結構的工具很是有做用
經常使用屬性
name:可選,表示數據庫表中該字段的名稱,默認與屬性名稱一致 nullable:可選,表示該字段是否容許爲null,默認爲true unique:可選,表示該字段是不是惟一標識,默認爲false length:可選,表示該字段的大小,僅對String類型的字段有效,默認爲255 (若是是主鍵不能使用默認值) insertable:可選,表示在ORM框架執行插入操做時,該字段是否應出現INSERT語句中,默認爲true updateable:可選,表示在ORM框架執行更新操做時,該字段是否應該出如今UPDATE語句中,默認爲true 對於一經建立就不能夠更改的字段,該屬性很是有用,如對於birthday字段
@Embedded
@Embedded是註釋屬性的,表示該屬性的類是嵌入類 注意:同時嵌入類也必須標註@Embeddable註解
@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(); } }
@Transient
可選,表示該屬性並不是一個到數據庫表的字段的映射,ORM框架將忽略該屬性,若是一個屬性並不是數據庫表的字段映射,就務必將其表示爲@Transient,不然ORM框架默認其註解爲@Basic
簡介
一對一單向外鍵關聯 一對一雙向外鍵關聯 一對一單向外鍵聯合主鍵 多對一單向外鍵關聯 一對多單向外鍵關聯 一對多雙向外鍵關聯 多對多單向外鍵關聯 多對多雙向外鍵關聯
實體之間的映射關係
一對一:一個公民對應一個身份證號碼 一對多(多對一):一個公民有多個銀行帳號 多對多:一個學生有多個老師,一個老師有多個學生
一對一單向外鍵
@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配置文件
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.url"> <![CDATA[ jdbc:mysql://localhost:3306/hibernatemtm?useUnicode=true&characterEncoding=utf8 ]]> </property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <property name="current_session_context_class">thread</property> <!-- 一對一單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetoonefk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonefk.IdCard"/> --> <!-- 一對一雙向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetoonebfk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonebfk.IdCard"/> --> <!-- 多對一單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.manytoonefk.Students"/> <mapping class="com.myimooc.hibernatera.manytoonefk.ClassRoom"/> --> <!-- 一對多單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanyfk.ClassRoom"/> --> <!-- 一對多雙向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanybfk.ClassRoom"/> --> <!-- 多對多單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.manytomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanyfk.Teachers"/> --> <!-- 多對多雙向外鍵關聯 --> <mapping class="com.myimooc.hibernatera.manytomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanybfk.Teachers"/> </session-factory> </hibernate-configuration>
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); } }
代碼演示
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(); } }
一對一雙向外鍵
主控方的配置同一對一單向外鍵關聯相同 @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配置文件
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.url"> <![CDATA[ jdbc:mysql://localhost:3306/hibernatemtm?useUnicode=true&characterEncoding=utf8 ]]> </property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <property name="current_session_context_class">thread</property> <!-- 一對一單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetoonefk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonefk.IdCard"/> --> <!-- 一對一雙向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetoonebfk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonebfk.IdCard"/> --> <!-- 多對一單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.manytoonefk.Students"/> <mapping class="com.myimooc.hibernatera.manytoonefk.ClassRoom"/> --> <!-- 一對多單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanyfk.ClassRoom"/> --> <!-- 一對多雙向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanybfk.ClassRoom"/> --> <!-- 多對多單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.manytomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanyfk.Teachers"/> --> <!-- 多對多雙向外鍵關聯 --> <mapping class="com.myimooc.hibernatera.manytomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanybfk.Teachers"/> </session-factory> </hibernate-configuration>
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(); } }
一對一雙向外鍵聯合主鍵
建立主鍵類 主鍵類必須實現serializable接口,重寫hashCode()和equals()方法 主鍵類:@Embeddable 實體類:@EmbeddedId
多對一單向外鍵
多方持有一方的引用,好比:多個學生對應一個班級(多對一) 在多方添加如下註解 @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配置文件
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.connection.url"> <![CDATA[ jdbc:mysql://localhost:3306/hibernatemtm?useUnicode=true&characterEncoding=utf8 ]]> </property> <property name="show_sql">true</property> <property name="hbm2ddl.auto">update</property> <property name="current_session_context_class">thread</property> <!-- 一對一單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetoonefk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonefk.IdCard"/> --> <!-- 一對一雙向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetoonebfk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonebfk.IdCard"/> --> <!-- 多對一單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.manytoonefk.Students"/> <mapping class="com.myimooc.hibernatera.manytoonefk.ClassRoom"/> --> <!-- 一對多單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanyfk.ClassRoom"/> --> <!-- 一對多雙向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.onetomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanybfk.ClassRoom"/> --> <!-- 多對多單向外鍵關聯 --> <!-- <mapping class="com.myimooc.hibernatera.manytomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanyfk.Teachers"/> --> <!-- 多對多雙向外鍵關聯 --> <mapping class="com.myimooc.hibernatera.manytomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanybfk.Teachers"/> </session-factory> </hibernate-configuration>
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); } }
代碼演示
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(); } }
一對多單向外鍵
一方持有多方的集合,一個班級有多個學生(一對多) 在一方添加如下註解 @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 Set<Students> stus; public ClassRoom() { } public ClassRoom(String cid, String cname) { this.cid = cid; this.cname = cname; } public Set<Students> getStus() { return stus; } public void setStus(Set<Students> 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(); // 建立服務註冊對象 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(), "計算機"); // 建立兩個集合 Set<Students> set1 = new HashSet<Students>(); set1.add(s1); set1.add(s2); Set<Students> set2 = new HashSet<Students>(); set2.add(s3); set2.add(s4); c1.setStus(set1); c2.setStus(set2); // 先保存學生 session.save(s1); session.save(s2); session.save(s3); session.save(s4); session.save(c1); session.save(c2); tx.commit(); } }
一對多(多對一)雙向外鍵
多方:多方持有一方的引用 在多方添加如下註解 @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER) @JoinColumn(name=」cid」) 一方:一方持有多方的集合 在一方添加如下註解 @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY) @JoinColumn(name=」cid」)
代碼演示
1.編寫Students類
package com.myimooc.hibernatera.onetomanybfk; 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") // 指定外鍵 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 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.onetomanybfk; 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 Set<Students> stus; public ClassRoom() { } public ClassRoom(String cid, String cname) { this.cid = cid; this.cname = cname; } public Set<Students> getStus() { return stus; } public void setStus(Set<Students> 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.onetomanybfk; 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(); // 建立服務註冊對象 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(), "計算機"); // 建立兩個集合 Set<Students> set1 = new HashSet<Students>(); set1.add(s1); set1.add(s2); Set<Students> set2 = new HashSet<Students>(); set2.add(s3); set2.add(s4); c1.setStus(set1); c2.setStus(set2); // 先保存學生 session.save(s1); session.save(s2); session.save(s3); session.save(s4); session.save(c1); session.save(c2); tx.commit(); } }
多對多單向外鍵
學生和教師構成多對多的關聯關係 其中一個多方持有另外一個多方的集合對象(學生持有教師的集合) 建立中間表 // 學生類中添加如下註解 @ManyToMany @JoinTable( name=」teachers_students」, joinColumns = {@JoinColumn(name=」sid」)}, inverseJoinColumns={@JoinColumn(name=」tid」)})
代碼演示
1.編寫Students類
package com.myimooc.hibernatera.manytomanyfk; import java.util.Date; import java.util.Set; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; /** * 多對多單向外鍵關聯 * 學生實體類(多方) * @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; // 學生持有教師的集合 @ManyToMany @JoinTable( name="teachers_students", joinColumns={@JoinColumn(name="sid")}, inverseJoinColumns={@JoinColumn(name="tid")} ) private Set<Teachers> teachers; @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 Set<Teachers> getTeachers() { return teachers; } public void setTeachers(Set<Teachers> teachers) { this.teachers = teachers; } 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.編寫Teachers類
package com.myimooc.hibernatera.manytomanyfk; 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 Teachers { /** 教師編號 */ @Id @GeneratedValue(generator="tid") @GenericGenerator(name="tid",strategy="assigned") @Column(length=4) private String tid; /** 教師姓名 */ private String tname; public Teachers(String tid, String tname) { this.tid = tid; this.tname = tname; } public Teachers() { } @Override public String toString() { return "Teachers [tid=" + tid + ", tname=" + tname + "]"; } public String getTid() { return tid; } public void setTid(String tid) { this.tid = tid; } public String getTname() { return tname; } public void setTname(String tname) { this.tname = tname; } }
3.修改hibernate配置文件
同上
4.編寫StudentsTest類
package com.myimooc.hibernatera.manytomanyfk; 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(); // 建立服務註冊對象 ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // 生成sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); SchemaExport export = new SchemaExport(config); export.create(true, true); } }
代碼演示
1.修改StudentsTest類
package com.myimooc.hibernatera.manytomanyfk; 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(); // 建立服務註冊對象 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(); // 建立教師對象 Teachers t1 = new Teachers("T001","張老師"); Teachers t2 = new Teachers("T002","李老師"); Teachers t3 = new Teachers("T003","陳老師"); Teachers t4 = new Teachers("T004","劉老師"); // 建立學生對象 Students s1 = new Students("張三","男",new Date(),"計算機"); Students s2 = new Students("李四","男",new Date(),"計算機"); Students s3 = new Students("王五","女",new Date(),"計算機"); Students s4 = new Students("趙六","女",new Date(),"計算機"); // 建立教師集合 Set<Teachers> set1 = new HashSet<Teachers>(); set1.add(t1); set1.add(t2); Set<Teachers> set2 = new HashSet<Teachers>(); set2.add(t3); set2.add(t4); Set<Teachers> set3 = new HashSet<Teachers>(); set3.add(t1); set3.add(t3); set3.add(t4); Set<Teachers> set4 = new HashSet<Teachers>(); set4.add(t2); set4.add(t3); set4.add(t4); // 設置學生教師 s1.setTeachers(set1); s2.setTeachers(set2); s3.setTeachers(set3); s4.setTeachers(set4); // 保存教師信息 session.save(t1); session.save(t2); session.save(t3); session.save(t4); // 保存學生信息 session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); } }
多對多雙向外鍵
雙方持有對方的集合對象,其中一方設置 // 教師類 @ManyToMany(mappedBy=」teachers」) // 學生類中添加如下註解 @ManyToMany @JoinTable( name=」teachers_students」, joinColumns = {@JoinColumn(name=」sid」)}, inverseJoinColumns={@JoinColumn(name=」tid」)})
代碼演示
1.編寫Students類
// 學生持有教師的集合 @ManyToMany @JoinTable( name="teachers_students", joinColumns={@JoinColumn(name="sid")}, inverseJoinColumns={@JoinColumn(name="tid")} ) private Set<Teachers> teachers;
2.編寫Teachers類
// 教師持有學生的集合 @ManyToMany(mappedBy="teachers") private Set<Students> students;
3.修改hibernate配置文件
同上
4.編寫StudentsTest類
同多對多單向外鍵關聯測試類
類級別註解
@Entity @Table @Embeddable
屬性級別註解
@Id @GeneratedValue @Column @Embedded @EmbeddedId @Transient
映射關係註解
@OneToOne:一對一單向外鍵 @OneToOne(mappedBy=」xxx」):一對一雙向外鍵關聯 @Embeddable和@EmbeddedId:一對一單向外鍵聯合主鍵 @ManyToOne和@JoinColumn:多對一單向外鍵關聯 @OneToMany和@JoinColumn:一對多單向外鍵關聯 @ManyToOne和@OneToMany 和@JoinColumn:一對多雙向外鍵關聯 @ManyToMany和@JoinColumn:多對多單向外鍵關聯 @ManyToMany(mappedBy=」xxx」)和@JoinTable:多對多雙向外鍵關聯