关联映射分为:
多对一关联映射、一对一关联映射、唯一外键关联、主键关联、一对多关联映射、多对多关联映射
根据关联关系链接的双方是否能够导航到彼此,我们将关联关系分为单向关联和双向关联
1.多对一关联映射 - many-to-one:
我们使用<many-to-one>元素来配置多对一关联关系
<many-to-one
name="propertyName"
column="column_name"
class="ClassName"
cascade="all|none|save-update|delete"
property-ref="propertyNameFromAssociatedClass"
not-null="true|false"
/>
name:待映射的持久化类的属性名。
column:column用于指定持久化类对应的表的外键字段名。
(3) class:关联的类的名字。
(4) cascade(级联):指明哪些操作会从父对象级联到关联的对象。
(5) property-ref:指定关联类的一个属性,这个属性将会和本外键相对应。 如果没有指定,会使用对方关联类的主键。
(6) not-null:使用DDL为外键字段生成一个非空约束。
<many-to-one name="group" column=“groupid”/>
执行代码后可得知我们建立了User到Group的外键关联
配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">sunrui1314</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/work</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="connection.characterEncoding">UTF-8</property>
<mapping class="com.entity.User" />
<mapping class="com.entity.Group" />
</session-factory>
</hibernate-configuration>