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>
本文出自 “黑足Sanji” 博客,谢绝转载!
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。