一 单向多对一生活举例
![](https://i-blog.csdnimg.cn/blog_migrate/669775b3d3f70668cdb035a547dfe9b2.png)
二 实现方式
多对一的关系和关系数据库中的外键参照关系最匹配,即在多方的表中的一个外键参照一方表的主键。
通过在多方持有一方的引用实现,需要在“多”的一端使用<many-to-one>配置。
三 单向多对一的配置
1 Student.java
package com.imooc.entity;
import java.io.Serializable;
public class Student implements Serializable {
private int sid;
private String sname;
private String sex;
// 在多方定义一个一方的引用
private Grade grade;
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Student() {
super();
}
public Student(String sname, String sex) {
super();
this.sname = sname;
this.sex = sex;
}
}
2 Student.hbm.xml配置
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping>
<class name="com.imooc.entity.Student" table="student">
<id name="sid" column="sid" type="java.lang.Integer">
<generator class="increment"></generator>
</id>
<property name="sname" type="java.lang.String">
<column name="sname" length="20" not-null="true"></column>
</property>
<property name="sex">
<column name="sex"></column>
</property>
<!-- 配置多对一关联关系 -->
<many-to-one name="grade" class="com.imooc.entity.Grade" column="gid" ></many-to-one>
</class>
</hibernate-mapping>
四 测试添加学生信息
1 测试代码
package com.imooc.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.imooc.entity.Grade;
import com.imooc.entity.Student;
import com.imooc.util.HibernateUtil;
/*
* 单向多对一(学生--->班级)
*/
public class Test02 {
public static void main(String[] args) {
save();
}
//保存
public static void save(){
Grade g=new Grade("Java一班","Java软件开发一班");
Student stu1=new Student("慕女神", "女");
Student stu2=new Student("小慕慕", "男");
//设置关联关系
stu1.setGrade(g);
stu2.setGrade(g);
Session session=HibernateUtil.getSession();
Transaction tx=session.beginTransaction();
session.save(g);
session.save(stu1);
session.save(stu2);
tx.commit();
HibernateUtil.closeSession(session);
}
}
2 测试结果
Hibernate: select max(gid) from grade
Hibernate: select max(sid) from student
Hibernate: insert into grade (gname, gdesc, gid) values (?, ?, ?)
Hibernate: insert into student (sname, sex, gid, sid) values (?, ?, ?, ?)
Hibernate: insert into student (sname, sex, gid, sid) values (?, ?, ?, ?)
![](https://i-blog.csdnimg.cn/blog_migrate/4e061a6b4d150385d77fa2f19b8d5ad1.png)