hibernate关系数据库的配置学习

双向关联的1对1关系:

public class People {
	private Integer id;
	private String name;
	private int age;
	private Student student; 
}
public class People {
	private Integer id;
	private String name;
	private int age;
	private Student student;
	}

配置文件:

	<class name="People" table="people">
  		......
  		//使用many-to-one是因为是双向关联的关系,student一方可能会有多个对应这一个
  		<many-to-one name="student" class="Student" cascade="all"
  			 unique="true">
  			 //在people类中对应的属性student在people表中对应的列为studentid
  			<column name="studentid"></column>	 
  		</many-to-one>
  	</class>

	<class name="Student" table="student">
		......
		<one-to-one name="people" class="People" property-ref="student" cascade="all" ></one-to-one>
	</class>

1对多或多对1的关系:

//多端
public class Address {
	private Integer id;
	private String stress;//街道
	private String room; //门牌号
	private People people; 
	}


public class People {
	private Integer id;
	private String name;
	private int age;
	private Set<Address> address = new HashSet<>();  //1端
}

配置文件:

<class name="Address" table="address">
		......
	 	<!-- 注意insert应该写在1方还是在多多方,如何insert的位置不对,会造成外键不能写入为null的情况 -->
	 	<many-to-one name="people" class="People" cascade="all" insert="true">
	 		//在address表中pid则对应address类中的people-----指定外键名
	 		<column name="pid"></column> 
	 	</many-to-one>
</class>

	<class name="People" table="people">
  		......
		<!-- 1对多关系的配置:1方的建写到多端 -->
  		<set name="address" cascade="all">
  			//告诉People表,查找address时主要看外键pid----声明外键及外键所在类
  			<key>
  				<column name="pid"></column>
  			</key>
  			<one-to-many class="Address"/>
  		</set>
  	</class>

多对多关系:

public class Student {
	private int id;
	private Timestamp date;
	private String room;
	private Set<Teacher> teachers = new HashSet<>();
}
public class Teacher {
	private int id;
	private String study;
	private Set<Student> students = new HashSet<>();
}

配置文件:

<class name="Student" table="student">
		......
		<set name="teachers" table="stu_teach" cascade="save-update">
		//声明teachers所对应的外键为teachid
			<key column="teachid"></key>
			<many-to-many class="Teacher" column="stuid"></many-to-many>
		</set>
	</class>

<class name="Teacher" table="teacher">
		......
		<set name="students" table="stu_teach" cascade="save-update">
			<key column="stuid"></key>
			<many-to-many class="Student" column="teachid"></many-to-many>
		</set>
	</class>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值