共享主键关联映射:让两个对象具有相同的主键值,以表明他们之间的一对一对应的关系;数据库表不会有额外的字段来维护他们之间的关系,仅通过表的主键来关联
一、单向关联映射:
One(维护端:Person)
<?xml version="1.0"encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="org.app.model"> <!-- 1-1:Person(维护端)【多】 to IdCard【一】) --> <class name="Person" table="t_person"> <idname="id"> <!-- 采用foreign生成策略,foreign会取得关联对象的标识 --> <generatorclass="foreign"> <!-- property值是关联的对象 --> <paramname="property">idCard</param> </generator> </id> <propertyname="name" /> <!-- one-to-one指示hibernate如何加载其关联对象,默认根据主键加载;也就是拿到关系字段值,根据另外一端的主键来加载关联对象 --> <!-- 维护关系:constrained=true:表示当前主键还是一个外键;指向另外一端的主键,也就是会生成外键约束语句(唯一) 【在‘多’端添加外键(‘多’端主键)指向‘一’的一端】 --> <one-to-onename="idCard" constrained="true"/> </class> </hibernate-mapping>
To
One(非维护端:IdCard)
<?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="org.app.model"> <class name="IdCard" table="t_idCard"> <id name="id"> <generator class="increment"/> </id> <property name="cardNo"/> </class> </hibernate-mapping>
public void testOneToOne(){ Session session = null; try { session = HibernateUtils.getSession(); session.beginTransaction(); // IdCard idCard = new IdCard(); idCard.setCardNo("111111"); // Person person = new Person(); person.setName("name"); person.setIdCard(idCard); // 一对一关联映射的特性决定了保存person时会先保存关联对象(idCard)(默认了级联属性);故保存person时可不用显示保存IdCard // 维护端要最后保存 session.save(person); session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); session.getTransaction().rollback(); } finally { HibernateUtils.closeSession(session); } }
二、双向关联映射
One(Person:维护端)
<?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="org.app.model"> <class name="Person" table="t_person"> <id name="id"> <generator class="foreign"> <param name="property">idCard</param> </generator> </id> <property name="name"/> <one-to-one name="idCard" constrained="true"></one-to-one> </class> </hibernate-mapping>
To
One(IdCard:非维护端)
<?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="org.app.model"> <class name="IdCard" table="t_idCard"> <id name="id"> <generator class="increment"/> </id> <property name="cardNo"/> <!-- 这里不影响存储(即设置先设置Person而不保存,再保存IdCard的时候并不会关联保存Person),只影响加载(维护端还是Person) --> <one-to-one name="person"/> </class> </hibernate-mapping>
时间: 2024-10-28 07:14:52