Time: Tuesday, 11 July 2017
Note: Part of the content of this article is from Mucho.com. @ Mu Course Net: http://www.imooc.com
Teaching Source: None
Learning source code: https://github.com/zccodere/s...
Chapter 1: Class level annotations
1-1 Introduction to this Chapter
Introduction to this chapter
Brief Introduction to Hibernate Annotations The relationship between JPA and Hibernate Hibernate Annotation Classification @Entity @Table @Embeddable schema and catalog
Brief Introduction to Hibernate Annotations
Purpose of using annotations: To simplify the configuration of tedious ORM mapping files (*. hbm)
The relationship between JPA and Hibernate
What is JPA Full name Java Persistence API JPA annotations are the norm and standard of Java EE The relationship between JPA and Hibernate:
JPA is a standard interface
Hibernate is implemented, but its function is a superset of JPA
How Hibernate Implements the Relation with JPA Through hibernate-annotation hibernate-entitymanager Implementation of three components of hibernate-core In general, JPA annotations are preferred in practical development.
This is more conducive to the transplantation and expansion of programs.
Classification of Hibernate Annotations
Class level annotations Attribute level annotations Annotation of Mapping Relations
Class level annotations
@ Entity: Represents an entity that corresponds to a database table @ Table: Properties of the configuration table @ Embeddable: Represents that the current class is an embedded class
1-2 Preparations
Review hibernate.cfg.xml
Create a maven project named hibernateca and add dependencies. The POM file is as follows
<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>
Create the hibernate.cfg.xml file in the src/main/resources directory
<!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> <!-- Specify the path of the mapping file --> <mapping class="com.myimooc.hibernateca.entity.Students"/> </session-factory> </hibernate-configuration>
1-3@Entity annotation
@Entity
@ Entity: Mapping Entity Classes @Entity(name="tableName") Name: optional, corresponding to a table in the database. If the table name is the same as the entity class name, it can be omitted. Note: Primary key properties of entity classes must be specified when using @Entity
Code demonstration
1. Writing Students Entity Classes
package com.myimooc.hibernateca.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * Student entity class * @author ZhangCheng on 2017-07-12 * */ //JPA Annotations @Entity(name="t_students") public class Students { /** Student ID */ @Id private Integer sid; /** Full name */ private String sname; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ 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. Configuration mapping
<! - Specify the path to the mapping file - > <mapping class="com.myimooc.hibernateca.entity.Students"/>
3. Write the StudentTest test test test class
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; /** * Unit test class * @author ZhangCheng on 2017-07-12 * */ public class StudentsTest { @Test public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating sessionFactory @SuppressWarnings("unused") SessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); SchemaExport export = new SchemaExport(config); export.create(true, true); } }
1-4@Table annotation
@Table
@Table(name="",catalog="",schema="") @ Entity configuration can only be used to annotate the class definition of the entity to represent the information of the database table corresponding to the entity. Name: optional, name of mapping table, default table name and entity name are identical, and table name should be specified only in case of inconsistency Catalog: Optional, indicating the catalog name of the directory, defaulting to Catalog("") Schema: optional, representing the schema Schema name, defaulting to Schema("")
Schema and catalog schema
schema and catalog
From the point of view of implementation, various database systems support Catalog and Schema in different ways.
Supplier support and Implementation
Code demonstration, modify Student class as follows
package com.myimooc.hibernateca.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * Student entity class * @author ZhangCheng on 2017-07-12 * */ //JPA Annotations //@Entity(name="t_students") @Entity @Table(name="t_students",schema="hibernatemtm") public class Students { /** Student ID */ @Id private Integer sid; /** Full name */ private String sname; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ 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 annotation
@Embeddable
@ Embeddable means that a non-Entity class can be embedded in another Entity class as an attribute.
Code demonstration
1. Writing Address classes
package com.myimooc.hibernateca.entity; import javax.persistence.Embeddable; /** * Address class (embedded class) * @author ZhangCheng on 2017-07-12 * */ // Representation is an embedded class whose object acts as an attribute in another entity class. @Embeddable public class Address { /** Zip code */ private String postCode; /** address */ private String address; /** Contact number */ 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. Modify the Student class as follows
package com.myimooc.hibernateca.entity; import java.util.Date; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * Student entity class * @author ZhangCheng on 2017-07-12 * */ //JPA Annotations //@Entity(name="t_students") @Entity @Table(name="t_students",schema="hibernatemtm") public class Students { /** Student ID */ @Id private Integer sid; /** Full name */ private String sname; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ private String major; /** address */ 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; } }
Chapter 2: Attribute Level Annotations
2-1 Introduction to this Chapter
Hibernate attribute level annotations
How to add: Write it on the property field or on the get accessor of the property @Id -@SequenceGenerator @GeneratedValue @Column @Embedded @EmbeddedId -@Lob -@Version -@Basic @Transient
2-2@Id annotation
@Id
@ Id: Must define the attributes of the primary key mapped to the database table. An entity class can have one or more attributes mapped to the primary key. Can be placed before the primary key attribute or get method Note: If multiple attributes are defined as primary key attributes, The entity class must implement the serializable interface
Copy the hibernateca project, renamed hibernateaa, POM and Hibernate configuration files are the same
Annotation 2-3@GeneratedValue (1)
@GeneratedValue
@GeneratedValue(strategy=GenerationType,generator="") Optional, user-defined primary key generation strategy Strategy represents the primary key generation strategy, with a value of ____________ Generation Type. AUTO: Automated selection based on underlying database (default) Generation Type. INDENTITY: Generated from the Identity field of the database Generation Type. SEQUENCE: Use Sequence to determine the value of the primary key GenerationType.TABLE: Use the specified table to determine the primary key value, combined with @TableGenerator
Use examples
Annotation 2-4@GeneratedValue (II)
Code demonstration
1. Modify the Students class
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; /** * Student entity class * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") @Entity @Table(name="t_students",schema="hibernatemtm") public class Students { /** Student ID */ /* Mode 1: Automatically generate primary keys @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer sid; */ /* Mode 2: Generating primary keys by manual assignment @Id @GeneratedValue(generator="sid") @GenericGenerator(name="sid",strategy="assigned")// @Column(length=8) private String sid; */ /* Mode 3: Use Compound Primary Key */ @EmbeddedId private StudentsPK pk; /** Full name */ private String sname; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ private String major; /** salary */ @Transient // Represents that the attribute will not be mapped by ORM to fields in the table private double salary; /** address */ @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; } }
Annotation 2-5@GeneratedValue (3)
Code demonstration
1. Modify the StudentsTest class
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; /** * Unit test class * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") public class StudentsTest { private SessionFactory sessionFactory = null; @Before public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); // SchemaExport export = new SchemaExport(config); // export.create(true, true); } @Test public void addStudents(){ // Create a session Session session = sessionFactory.getCurrentSession(); // Create a transaction Transaction tx = session.beginTransaction(); // Create a Student Object Address address = new Address("700005","Hubei Wudang Mountains","18991167346"); // Students = new students ("S0000002", "Zhang Sanfeng", "Male", "new Date(),"Taijiquan","address); // // session.save(s); tx.commit(); } @Test public void addStudentsByPk(){ // Create a session Session session = sessionFactory.getCurrentSession(); // Create a transaction Transaction tx = session.beginTransaction(); // Create a Student Object Address address = new Address("700005","Hubei Wudang Mountains","18991167346"); // Creating Student Primary Key Objects StudentsPK pk = new StudentsPK(); pk.setId("123456789012345678"); pk.setSid("1235241231"); Students s = new Students(pk,"Zhang Sanfeng","male",new Date(),"Taiji boxing",address); session.save(s); tx.commit(); } }
2-6@Column annotation
@Column
@ Column: You can map attributes to columns and use this annotation to override default values @ Column describes the detailed definition of this field in a database table This is very useful for generating database table structure tools based on JPA annotations.
Common attributes
Name: optional, indicating the name of the field in the database table, which is the same as the attribute name by default nullable: optional, indicating whether the field is allowed to be null by default to true Unique: optional, indicating whether the field is a unique identifier, default to false? length: optional, indicating the size of the field, valid only for fields of String type, default 255 (If the primary key cannot use the default value) insertable: optional, indicating whether the field should appear in the INSERT statement when the ORM framework performs the insert operation, defaulting to true updateable: optional, indicating whether the field should appear in the UPDATE statement when the ORM framework performs an update operation, defaulting to true This property is useful for fields that cannot be changed once created, such as birthday fields.
2-7@Embedded annotation
@Embedded
@ Embedded is an annotated attribute, and the class representing that attribute is an embedded class. Note: The embedded class must also be annotated with the @Embeddable annotation
2-8@EmbeddedId annotation
@EmbeddedId
@ EmbeddedId uses embedded primary key classes to implement composite primary keys Note: Embedded primary key classes Serializable interface must be implemented There must be a default public parameterless construction method equals and hashCode methods must be overridden
Code demonstration
1. Write Students PK class
package com.myimooc.hibernateaa.entity; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Embeddable; /** * Student Key Category * @author ZhangCheng on 2017-07-12 * */ @Embeddable public class StudentsPK implements Serializable{ private static final long serialVersionUID = 1L; /** Provincial Certificate Number */ @Column(length=18) private String id; /** Student 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. Modify the Students class
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; /** * Student entity class * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") @Entity @Table(name="t_students",schema="hibernatemtm") public class Students { /** Student ID */ /* Mode 1: Automatically generate primary keys @Id @GeneratedValue(strategy=GenerationType.AUTO) private Integer sid; */ /* Mode 2: Generating primary keys by manual assignment @Id @GeneratedValue(generator="sid") @GenericGenerator(name="sid",strategy="assigned")// @Column(length=8) private String sid; */ /* Mode 3: Use Compound Primary Key */ @EmbeddedId private StudentsPK pk; /** Full name */ private String sname; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ private String major; /** salary */ @Transient // Represents that the attribute will not be mapped by ORM to fields in the table private double salary; /** address */ @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. Modify the StudentsTest class
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; /** * Unit test class * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") public class StudentsTest { private SessionFactory sessionFactory = null; @Before public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); // SchemaExport export = new SchemaExport(config); // export.create(true, true); } @Test public void addStudents(){ // Create a session Session session = sessionFactory.getCurrentSession(); // Create a transaction Transaction tx = session.beginTransaction(); // Create a Student Object Address address = new Address("700005","Hubei Wudang Mountains","18991167346"); // Students = new students ("S0000002", "Zhang Sanfeng", "Male", "new Date(),"Taijiquan","address); // // session.save(s); tx.commit(); } @Test public void addStudentsByPk(){ // Create a session Session session = sessionFactory.getCurrentSession(); // Create a transaction Transaction tx = session.beginTransaction(); // Create a Student Object Address address = new Address("700005","Hubei Wudang Mountains","18991167346"); // Creating Student Primary Key Objects StudentsPK pk = new StudentsPK(); pk.setId("123456789012345678"); pk.setSid("1235241231"); Students s = new Students(pk,"Zhang Sanfeng","male",new Date(),"Taiji boxing",address); session.save(s); tx.commit(); } }
2-9@Transient annotation
@Transient
Optionally, the ORM framework ignores the attribute that is not a field mapping to a database table. If an attribute is not a field mapping to a database table, it must be expressed as @Transient. Otherwise, the ORM framework defaults to its annotation @Basic.
Chapter 3: Relevance mapping annotations
3-1 Introduction to this Chapter
brief introduction
One-to-one single-to-foreign key Association One-to-one bidirectional foreign key Association One-to-one single-to-external key union primary key Many-to-one one one-to-foreign key Association One-to-many single-to-foreign key Association One-to-many bidirectional foreign key Association Multiple-to-many single-to-foreign key Association Multi-to-multi bidirectional foreign key Association
Relations between 3-2 Entities
Mapping relationship between entities
One-to-one: A citizen corresponds to an ID number One-to-many (many-to-one): A citizen has multiple bank accounts Many-to-many: A student has more than one teacher and a teacher has more than one student.
3-3 one-to-one single-to-foreign key Association (1)
One-to-one single-to-foreign key
@OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="pid",unique=true) Note: Foreign key objects should be saved before main table objects are saved.
Copy the hibernateca project, renamed hibernatera, POM and Hibernate configuration files are the same
Code demonstration
1. Write Students class
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; /** * One-to-one single-to-foreign key Association * Student entity class * @author ZhangCheng on 2017-07-12 * */ @Entity public class Students { /** Student ID */ @Id @GeneratedValue private Integer sid; /** Identity Card Category */ @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="pid",unique=true) private IdCard card; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ 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. Write the IdCard class
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; /** * One-to-one single-to-foreign key Association * Identification body class * @author ZhangCheng on 2017-07-12 * */ @Entity public class IdCard { @Id @GeneratedValue(generator = "pid") @GenericGenerator(name="pid",strategy="assigned") @Column(length=18) /** ID card No. */ private String pid; /** Name of student */ 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. Modify Hibernate configuration file
<!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> <!-- One-to-one single-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetoonefk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonefk.IdCard"/> --> <!-- One-to-one bidirectional foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetoonebfk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonebfk.IdCard"/> --> <!-- Many-to-one one one-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.manytoonefk.Students"/> <mapping class="com.myimooc.hibernatera.manytoonefk.ClassRoom"/> --> <!-- One-to-many single-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanyfk.ClassRoom"/> --> <!-- One-to-many bidirectional foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanybfk.ClassRoom"/> --> <!-- Multiple-to-many single-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.manytomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanyfk.Teachers"/> --> <!-- Multi-to-multi bidirectional foreign key Association --> <mapping class="com.myimooc.hibernatera.manytomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanybfk.Teachers"/> </session-factory> </hibernate-configuration>
4. Write StudentsTest class
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; /** * One-to-one pair of single foreign key associations * Unit test class * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") public class StudentsTest { private SessionFactory sessionFactory = null; @Before public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); // SchemaExport export = new SchemaExport(config); // // export.create(true, true); } }
3-4 one-to-one single-to-foreign key Association (2)
Code demonstration
1. Modify the StudentsTest class
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; /** * One-to-one pair of single foreign key associations * Unit test class * @author ZhangCheng on 2017-07-12 * */ @SuppressWarnings("unused") public class StudentsTest { private SessionFactory sessionFactory = null; @Before public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); // SchemaExport export = new SchemaExport(config); // // export.create(true, true); } /** * One-to-one and one-to-one key Association save test */ @Test public void addStudents(){ Session session = sessionFactory.getCurrentSession(); // Generate an ID card object IdCard card = new IdCard("123456789012345678","Zhang Wuji"); Transaction tx = session.beginTransaction(); // Generating Student Objects Students s = new Students(card, "male", new Date(), "Taiji boxing"); // Save the object of ID card class first session.save(card); session.save(s); tx.commit(); } }
3-5 one-to-one two-way foreign key Association
One-to-one two-way foreign key
The configuration of the main control is the same as that of the one-to-one one one-to-external key association. @ OneToOne(mappedBy="card")//accused party The mappedBy property must be set for bidirectional associations. Because two-way association can only be controlled by one party. It is impossible to set foreign keys on both sides to save the relationship, otherwise neither side can save it.
Code demonstration
1. Write Students class
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; /** * One-to-one bidirectional foreign key Association * Student entity class * @author ZhangCheng on 2017-07-12 * */ @Entity public class Students { /** Student ID */ @Id @GeneratedValue private Integer sid; /** Identity Card Category */ @OneToOne(cascade=CascadeType.ALL) @JoinColumn(name="pid",unique=true) private IdCard card; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ 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. Write the IdCard class
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; /** * One-to-one bidirectional foreign key Association * Identification body class * @author ZhangCheng on 2017-07-12 * */ @Entity public class IdCard { @Id @GeneratedValue(generator = "pid") @GenericGenerator(name="pid",strategy="assigned") @Column(length=18) /** ID card No. */ private String pid; /** Name of student */ private String sname; /** Student citation */ @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. Modify hibernate configuration file
<!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> <!-- One-to-one single-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetoonefk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonefk.IdCard"/> --> <!-- One-to-one bidirectional foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetoonebfk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonebfk.IdCard"/> --> <!-- Many-to-one one one-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.manytoonefk.Students"/> <mapping class="com.myimooc.hibernatera.manytoonefk.ClassRoom"/> --> <!-- One-to-many single-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanyfk.ClassRoom"/> --> <!-- One-to-many bidirectional foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanybfk.ClassRoom"/> --> <!-- Multiple-to-many single-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.manytomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanyfk.Teachers"/> --> <!-- Multi-to-multi bidirectional foreign key Association --> <mapping class="com.myimooc.hibernatera.manytomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanybfk.Teachers"/> </session-factory> </hibernate-configuration>
4. Write StudentsTest class
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; /** * One-to-one bidirectional foreign key Association * Unit test class * @author ZhangCheng on 2017-07-12 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); SchemaExport export = new SchemaExport(config); export.create(true, true); } /** * One-to-one two-way foreign key Association save test */ @Test public void addStudents(){ Session session = sessionFactory.getCurrentSession(); // Generate an ID card object IdCard card = new IdCard("123456789012345678","Zhang Wuji"); Transaction tx = session.beginTransaction(); // Generating Student Objects Students s = new Students(card, "male", new Date(), "Taiji boxing"); // Save the object of ID card class first session.save(card); session.save(s); tx.commit(); } }
3-6 One-to-One Single-to-Outward Key Joint Primary Key
One-to-one two-way foreign key union primary key
Create primary key class The primary key class must implement the serializable interface, rewriting hashCode() and equals() methods Primary key class: @Embeddable Entity class: @EmbeddedId
3-7 Many-to-One External Key Association (I)
Many-to-One Outward Key
Multiple holders of one-sided references, such as: multiple students corresponding to a class (many-to-one) Add the following annotations to multiple parties @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER) @JoinColumn(name="cid",referencedColumnName="CID")
Code demonstration
1. Write Students class
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; /** * Many-to-one one one-to-foreign key Association * Student entity class (multi-party) * @author ZhangCheng on 2017-07-13 * */ @Entity public class Students { /** Student ID */ @Id @GeneratedValue private Integer sid; /** Name of student */ private String sname; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ private String major; // Reference by multi-party holders @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)// Configuration Cascade Relations and Grabbing Strategies @JoinColumn(name="cid",referencedColumnName="CID") // Specify foreign keys 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. Writing ClassRoom classes
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; /** * Many-to-one one one-to-foreign key Association * Class entity class (one side) * @author ZhangCheng on 2017-07-13 * */ @Entity public class ClassRoom { /** Class Number */ @Id @GeneratedValue(generator="cid") @GenericGenerator(name="cid",strategy="assigned") @Column(length=4) private String cid; /** Class name */ 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. Modify hibernate configuration file
<!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> <!-- One-to-one single-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetoonefk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonefk.IdCard"/> --> <!-- One-to-one bidirectional foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetoonebfk.Students"/> <mapping class="com.myimooc.hibernatera.onetoonebfk.IdCard"/> --> <!-- Many-to-one one one-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.manytoonefk.Students"/> <mapping class="com.myimooc.hibernatera.manytoonefk.ClassRoom"/> --> <!-- One-to-many single-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanyfk.ClassRoom"/> --> <!-- One-to-many bidirectional foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.onetomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.onetomanybfk.ClassRoom"/> --> <!-- Multiple-to-many single-to-foreign key Association --> <!-- <mapping class="com.myimooc.hibernatera.manytomanyfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanyfk.Teachers"/> --> <!-- Multi-to-multi bidirectional foreign key Association --> <mapping class="com.myimooc.hibernatera.manytomanybfk.Students"/> <mapping class="com.myimooc.hibernatera.manytomanybfk.Teachers"/> </session-factory> </hibernate-configuration>
4. Write StudentsTest class
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; /** * Many-to-one one one-to-foreign key Association * Unit test class * @author ZhangCheng on 2017-07-13 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); SchemaExport export = new SchemaExport(config); export.create(true, true); } }
3-8 many-to-one single-to-foreign key Association (2)
Code demonstration
1. Modify the StudentsTest class
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; /** * Many-to-one one one-to-foreign key Association * Unit test class * @author ZhangCheng on 2017-07-13 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating 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(); // Creating Class Objects ClassRoom c1 = new ClassRoom("C001","software engineering"); ClassRoom c2 = new ClassRoom("C002","Network Engineering"); // Creating Student Objects Students s1 = new Students("Zhang San","male", new Date(), "Computer"); Students s2 = new Students("Li Si","male", new Date(), "Computer"); Students s3 = new Students("Wang Wu","female", new Date(), "Computer"); Students s4 = new Students("Zhao Liu","female", new Date(), "Computer"); s1.setClassRoom(c1); s2.setClassRoom(c1); s3.setClassRoom(c2); s4.setClassRoom(c2); // Save the class first session.save(c1); session.save(c2); session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); } }
3-9 One-to-Many One-to-One External Key Association
One-to-many single-to-foreign key
One party holds a multi-party collection, and one class has more than one student (one-to-many) Add the following annotations to one side @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY) @JoinColumn(name="cid")
Summary of Grabbing Strategies
Many-to-one time Multiple Settings of EAGER: Indicates Active Loading One side sets LAZY: to indicate lazy loading
Code demonstration
1. Write Students class
package com.myimooc.hibernatera.onetomanyfk; import java.util.Date; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; /** * One-to-many single-to-foreign key Association * Student entity class (multi-party) * @author ZhangCheng on 2017-07-13 * */ @Entity public class Students { /** Student ID */ @Id @GeneratedValue private Integer sid; /** Name of student */ private String sname; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ 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. Writing ClassRoom classes
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; /** * One-to-many single-to-foreign key Association * Class entity class (one side) * @author ZhangCheng on 2017-07-13 * */ @Entity public class ClassRoom { /** Class Number */ @Id @GeneratedValue(generator="cid") @GenericGenerator(name="cid",strategy="assigned") @Column(length=4) private String cid; /** Class name */ private String cname; // A party holds a collection of parties. @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. Modify hibernate configuration file
Ditto
4. Write StudentsTest class
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; /** * One-to-many single-to-foreign key Association * Unit test class * @author ZhangCheng on 2017-07-13 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating 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(); // Creating Class Objects ClassRoom c1 = new ClassRoom("C001","software engineering"); ClassRoom c2 = new ClassRoom("C002","Network Engineering"); // Creating Student Objects Students s1 = new Students("Zhang San","male", new Date(), "Computer"); Students s2 = new Students("Li Si","male", new Date(), "Computer"); Students s3 = new Students("Wang Wu","female", new Date(), "Computer"); Students s4 = new Students("Zhao Liu","female", new Date(), "Computer"); // Create two collections 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); // Save the students first session.save(s1); session.save(s2); session.save(s3); session.save(s4); session.save(c1); session.save(c2); tx.commit(); } }
3-10 one-to-many bidirectional foreign key Association
One-to-many (many-to-one) two-way foreign key
Multi-party: the reference of multi-party holders Add the following annotations to multiple parties @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER) @JoinColumn(name="cid") One side: One side holds a collection of multiple parties. Add the following annotations to one side @OneToMany(cascade={CascadeType.ALL},fetch=FetchType.LAZY) @JoinColumn(name="cid")
Code demonstration
1. Write Students class
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; /** * One-to-many bidirectional foreign key Association * Student entity class (multi-party) * @author ZhangCheng on 2017-07-13 * */ @Entity public class Students { /** Student ID */ @Id @GeneratedValue private Integer sid; /** Name of student */ private String sname; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ private String major; // Reference by multi-party holders @ManyToOne(cascade={CascadeType.ALL},fetch=FetchType.EAGER)// Configuration Cascade Relations and Grabbing Strategies @JoinColumn(name="cid") // Specify foreign keys 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. Writing ClassRoom classes
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; /** * One-to-many bidirectional foreign key Association * Class entity class (one side) * @author ZhangCheng on 2017-07-13 * */ @Entity public class ClassRoom { /** Class Number */ @Id @GeneratedValue(generator="cid") @GenericGenerator(name="cid",strategy="assigned") @Column(length=4) private String cid; /** Class name */ private String cname; // A party holds a collection of parties. @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. Modify hibernate configuration file
Ditto
4. Write StudentsTest class
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; /** * One-to-many bidirectional foreign key Association * Unit test class * @author ZhangCheng on 2017-07-13 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating 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(); // Creating Class Objects ClassRoom c1 = new ClassRoom("C001","software engineering"); ClassRoom c2 = new ClassRoom("C002","Network Engineering"); // Creating Student Objects Students s1 = new Students("Zhang San","male", new Date(), "Computer"); Students s2 = new Students("Li Si","male", new Date(), "Computer"); Students s3 = new Students("Wang Wu","female", new Date(), "Computer"); Students s4 = new Students("Zhao Liu","female", new Date(), "Computer"); // Create two collections 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); // Save the students first session.save(s1); session.save(s2); session.save(s3); session.save(s4); session.save(c1); session.save(c2); tx.commit(); } }
3-11 Multiple-to-Many Single-to-Foreign Key Association (I)
Many-to-many single-to-foreign key
Many-to-many relationship between students and teachers One party holds the other party's collection object (the student holds the teacher's collection) Create intermediate tables // Add the following notes to the student class @ManyToMany @JoinTable( name="teachers_students", joinColumns = {@JoinColumn(name="sid")}, inverseJoinColumns={@JoinColumn(name="tid")})
Code demonstration
1. Write Students class
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; /** * Multiple-to-many single-to-foreign key Association * Student entity class (multi-party) * @author ZhangCheng on 2017-07-13 * */ @Entity public class Students { /** Student ID */ @Id @GeneratedValue private Integer sid; /** Name of student */ private String sname; /** Gender */ private String gender; /** Date of birth */ private Date birthday; /** major */ private String major; // Students hold a collection of Teachers @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. Writing Teachers Classes
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; /** * Multiple-to-many single-to-foreign key Association * Teachers'Substantive Category (Multi-party) * @author ZhangCheng on 2017-07-13 * */ @Entity public class Teachers { /** Teacher Number */ @Id @GeneratedValue(generator="tid") @GenericGenerator(name="tid",strategy="assigned") @Column(length=4) private String tid; /** Name of Teacher */ 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. Modify hibernate configuration file
Ditto
4. Write StudentsTest class
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; /** * Multiple-to-many single-to-foreign key Association * Unit test class * @author ZhangCheng on 2017-07-13 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating sessionFactory sessionFactory = config.buildSessionFactory(ServiceRegistry); SchemaExport export = new SchemaExport(config); export.create(true, true); } }
3-12 Multiple-to-Many Single-to-Foreign Key Association (II)
Code demonstration
1. Modify the StudentsTest class
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; /** * Multiple-to-many single-to-foreign key Association * Unit test class * @author ZhangCheng on 2017-07-13 * */ public class StudentsTest { private SessionFactory sessionFactory = null; @Before //@Test public void schemaExportTest(){ // Create hibernate configuration objects Configuration config = new Configuration().configure(); // Creating Service Registration Objects ServiceRegistry ServiceRegistry = new ServiceRegistryBuilder() .applySettings(config.getProperties()).buildServiceRegistry(); // Generating 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(); // Creating Teacher Objects Teachers t1 = new Teachers("T001","Mr. Zhang"); Teachers t2 = new Teachers("T002","Miss Li"); Teachers t3 = new Teachers("T003","Mr. Chen"); Teachers t4 = new Teachers("T004","Miss Liu"); // Creating Student Objects Students s1 = new Students("Zhang San","male",new Date(),"Computer"); Students s2 = new Students("Li Si","male",new Date(),"Computer"); Students s3 = new Students("Wang Wu","female",new Date(),"Computer"); Students s4 = new Students("Zhao Liu","female",new Date(),"Computer"); // Creating Teachers'Collection 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); // Setting up Student Teachers s1.setTeachers(set1); s2.setTeachers(set2); s3.setTeachers(set3); s4.setTeachers(set4); // Preserving Teacher Information session.save(t1); session.save(t2); session.save(t3); session.save(t4); // Preserving Student Information session.save(s1); session.save(s2); session.save(s3); session.save(s4); tx.commit(); } }
3-13 Multi-to-Multi Bidirectional Foreign Key Association
Many-to-many bidirectional foreign keys
Each party holds the other party's collection object, and one of them sets it up. // Teachers @ManyToMany(mappedBy="teachers") // Add the following notes to the student class @ManyToMany @JoinTable( name="teachers_students", joinColumns = {@JoinColumn(name="sid")}, inverseJoinColumns={@JoinColumn(name="tid")})
Code demonstration
1. Write Students class
// Students hold a collection of Teachers @ManyToMany @JoinTable( name="teachers_students", joinColumns={@JoinColumn(name="sid")}, inverseJoinColumns={@JoinColumn(name="tid")} ) private Set<Teachers> teachers;
2. Writing Teachers Classes
// Teachers hold collections of students @ManyToMany(mappedBy="teachers") private Set<Students> students;
3. Modify hibernate configuration file
Ditto
4. Write StudentsTest class
Multiple-to-many single-to-foreign key association test classes
Chapter IV: Curriculum Summary
4-1 Course Summary
Class level annotations
@Entity @Table @Embeddable
Attribute level annotations
@Id @GeneratedValue @Column @Embedded @EmbeddedId @Transient
Annotation of Mapping Relations
@ OneToOne: One-to-one, one-to-one, one-to-one, one-to-one external keys @ OneToOne(mappedBy= "xxx"): One-to-one two-way foreign key Association @ Embeddable and @EmbeddedId: One-to-one, one-to-one union primary key @ ManyToOne and @JoinColumn: Many-to-one one associations with foreign keys @ OneToMany and @JoinColumn: One-to-many single-to-foreign key associations @ ManyToOne and @OneToMany and @JoinColumn: One-to-many bidirectional foreign key associations @ ManyToMany and @JoinColumn: Multiple-to-many single-to-foreign key associations @ ManyToMany(mappedBy= "xxx") and @JoinTable: Multiple-to-many bidirectional foreign key associations