Hibernate many-to-one Association
A working Group can contain multiple users. A User belongs to only one Group, which is a typical multi-to-one relationship. In the multi-to-one relationship, the correct database design is to add a Group foreign key to the Multi-Party (here the User side. If the database design is the opposite, redundancy will occur. See the following example:
Friendly reminder: this is the wrong design method:
GroupId |
GroupName |
UserId |
1 |
Group_1 |
1 |
1 |
Group_1 |
2 |
UserId |
UserName |
1 |
Moluo |
2 |
Xingzhe |
In this way, when a foreign key Association is set on this side (that is, the Group side), redundancy will occur (a Group has N users, in this way, we have to repeat the redundant GroupId and GroupName N times. Therefore, in many-to-one scenarios, the database design must include a foreign key in many scenarios!
First, write the one-to-one association of the Annotation Version:
Create a Group class first:
package com.hibernate.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name=_Group)public class Group {private int id;private String name;@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}Recreate the User class:
package com.hibernate.model;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.Id;import javax.persistence.ManyToOne;import javax.persistence.Table;@Entity@Table(name=_User)public class User {private int id;private String name;private Group group;@ManyToOnepublic Group getGroup() {return group;}public void setGroup(Group group) {this.group = group;}@Id@GeneratedValuepublic int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}}Add the foreign key of the group to multiple nodes and specify @ manyToOne in the get method.
Configuration file:
Test cases:
package com.hibernate.model;import static org.junit.Assert.*;import org.hibernate.SessionFactory;import org.hibernate.cfg.AnnotationConfiguration;import org.hibernate.tool.hbm2ddl.SchemaExport;import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.Test;public class ORMappingTest {public static SessionFactory sf = null;//@BeforeClasspublic static void beforeClass(){try{sf = new AnnotationConfiguration().configure().buildSessionFactory();}catch(Exception e) {e.printStackTrace();}finally{}}@Testpublic void testSchemaExport(){new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);}//@AfterClasspublic static void afterClass(){sf.close();}}First, write the multi-to-one association of the xml version:
Group and User classes and test cases are the same as above.