Hibernate双向多对一实战
程序员文章站
2022-07-11 20:23:09
...
一 双向多对一生活举例
二 Grade.hbm.xml配置一对多关联关系
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
<hibernate-mapping>
<class name="com.imooc.entity.Grade" table="grade">
<id name="gid" column="gid" type="java.lang.Integer">
<generator class="increment"></generator>
</id>
<property name="gname" type="java.lang.String">
<column name="gname" length="20" not-null="true"></column>
</property>
<property name="gdesc">
<column name="gdesc"></column>
</property>
<!-- 配置一对多关联关系 -->
<set name="students" table="student">
<key column="gid"></key>
<one-to-many class="com.imooc.entity.Student"/>
</set>
</class>
</hibernate-mapping>
三 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>
四 测试代码
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("小慕慕", "男");
//设置关联关系
g.getStudents().add(stu1);
g.getStudents().add(stu2);
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);
}
}
五 测试结果
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 (?, ?, ?, ?)
Hibernate: update student set gid=? where sid=?
Hibernate: update student set gid=? where sid=?
从后台输出来看,多余了两条update语句。
上一篇: hibernate
下一篇: Hibernate中出现的异常