hibernate多对一关联映射:
实体类 (POJO) |
public class Student{ private int stuId; private String stuNum; private String stuName; private ClassRoom cr; } |
public class ClassRoom{ private int claId; private String claName; } |
||||||||||||||||||||
映射文件 |
<class name=” Student” table=”tb_student”> <id name=” stuId” column=” stu_id”> <generator class=”native”/> </id> <property name=” stuNum” column=” stu_num”/> <property name=” stuName” column=” stu_name”/> <many-to-one name=”cr” column=”cid” /> </class> |
<class name=”ClassRoom” table=”tb_class”> <id name=” claId” column=” class_id”> <generator class=”native”/> </id> <property name=” claName” column=”class_name”/> </class> |
||||||||||||||||||||
表 |
|
|
||||||||||||||||||||
<many-to-one name="cr" column="cid" not-null="true" cascade="all"></many-to-one> not-null="true:要求外键不能为null,一个学生必须对应一个班级 cascade="all":当添加s,首先执行saveOrUpdate(cr), 然后执行session.save(s) |
映射文件:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="com.softeem.crud.pojos"> <class name="Group" table="tb_group"> <id name="groupId" column="group_id"> <generator class="native"></generator> </id> <property name="groupName" column="group_name"></property> </class> <class name="User" table="tb_user"> <id name="userId" column="user_id"> <generator class="native"></generator> </id> <property name="userName" column="user_name"/> <property name="userPwd" column="user_pwd"/> <!--cascade="all"级联操作 --> <many-to-one name="group" class="Group" column="gid" not-null="true" cascade="all"></many-to-one> </class> </hibernate-mapping>
时间: 2024-10-03 22:41:50