使用连接表的单向关联(Unidirectional associations with join tables)

1.one-to-many:基于连接表的单向一对多关联,应该优先被采用。请注意,通过制定unique=“true”,我们可以把多样性从多对多改变为一对多。

<class name="Person">
	<id name="id" column="personId">
		<generator class="native"/>
	</id>
	<set name="addresses" table="PersonAddress">
		<key column="personId"/>
		<many-to-many column="addressId"
			unique="true"
			class="Address"/>
	</set>
</class>

<class name="Address">
	<id name="id" column="addressId">
		<generator class="native"/>
	</id>
</class>

2.many-to-one:基于连接表的单向多对一关联在关联关系可选的情况下应用也很普遍。

<class name="Person">
	<id name="id" column="personId">
		<generator class="native"/>
	</id>
	<join table="PersonAddress" optional="true">
		<key column="personId" unique="true"/>
		<many-to-one name="address" 
			column="addressId"
			not-null="true"/>
	</join>
</class>

<class name="Address">
	<id name="id" column="addressId">
		<generator class="native"/>
	</id>
</class>


3.one-to-one:基于连接表的单向一对一关联也是可行的,但非常少见。

<class name="Person">
	<id name="id" column="personId">
		<generator class="native"/>
	</id>
	<join table="PersonAddress" optional="true">
		<key column="personId"
			unique="true"/>
		<many-to-one name="address"
			column="addressId"
			not-null="true"
			unique="true"/>
	</join>
</class>

<class name="Address">
	<id name="id" column="addressId">
		<generator class="native"/>
	</id>
</class>

4.many-to-many:多对多

<class name="Person">
	<id name="id" column="personId">
		<generator class="native"/>
	</id>
	<set name="addresses" table="PersonAddress">
		<key column="personId"/>
		<many-to-many column="addressId"
			class="Address"/>
	</set>
</class>

<class name="Address">
	<id name="id" column="addressId">
		<generator class="native"/>
	</id>
</class>



你可能感兴趣的:(使用连接表的单向关联(Unidirectional associations with join tables))