in the previous article, we said that a multi-pair and one-to-many mapping principle is the same, all at one end of a foreign key to point to one end.
The difference is that the maintenance relationship is different.
- Many-to-one maintenance relationship: Multi-point-to-one relationship, if you maintain a multi-point-to-one relationship, then load more time will load up
- One-to-many maintenance relationship: a point-to-many relationship, if you maintain a point-to-many relationship, then load one will be loaded up
A one-to-many mapping consists of two mapping methods:
1. One-to-many
Object Model Diagram:
Relational Model diagram:
Classes.hbm.xml configuration file
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
Student.hbm.xml configuration file
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
Why not let one end maintain relationships?
- Many end student do not know the existence of classes, (that is, student does not maintain the relationship with classes) so when saving student the relationship field classesid is null, if the field is set to non-empty, the data will not be saved.
- Student does not maintain the relationship, and classes maintain the relationship, classes will issue an extra UPDATE statement, to ensure that class and student have a relationship, so load classes when the classes corresponding students can be loaded up.
To address this disadvantage, Hibernate provides a second mapping method, bidirectional one-to-many mappings.
2. Bidirectional one-to-manyObject Model Diagram
Relational Model Diagram
a one-to-many bidirectional association mapping method:
- Use <key> tags at one end of the set, and add a foreign key to one end
- Use <many-to-one> tags on multiple end
!!! Note that the:<key> tag is consistent with the fields that are added to the <many-to-one> tag, or it can result in data confusion
Classes.hbm.xml configuration file
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
Student.hbm.xml configuration file
<?xml version= "1.0"? ><! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "http://hibernate.sourceforge.net/ Hibernate-mapping-3.0.dtd ">
!!! Note: The goal of a one-to-many bi-directional association is to solve a multiple-way association defect rather than demand-driven.
Hibernate mapping parsing--correlation mapping (ii)