one-to-one双向关联映射第二种

来源:互联网 发布:windows命令行列出文件 编辑:程序博客网 时间:2024/06/15 09:30

Wife.java

package com.model;public class Wife {private int id;private String name;private Husband husband;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Husband getHusband() {return husband;}public void setHusband(Husband husband) {this.husband = husband;}}

Husband.java

package com.model;public class Husband {private int id;private String name;private Wife wife;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Wife getWife() {return wife;}public void setWife(Wife wife) {this.wife = wife;}}

Wife.hbm.xml

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><!-- ORM映射文件 -->        <hibernate-mapping package="com.model"><class name="Wife" table="wife"><id name="id"><generator class="foreign"><param name="property">husband</param></generator></id><property name="name" column="name"></property><one-to-one name="husband" class="Husband" constrained="true"></one-to-one></class></hibernate-mapping>

Husband.hbm.xml

<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><!-- ORM映射文件 -->        <hibernate-mapping package="com.model"><class name="Husband" table="husband"><id name="id"><generator class="native"></generator></id><property name="name" column="name"></property><one-to-one name="wife" class="Wife"></one-to-one></class></hibernate-mapping>

单元测试:

@Testpublic void t(){Session session = HibernateUtil.getInstance().getSession();session.beginTransaction();Husband h = new Husband();h.setName("h");Wife w = new Wife();w.setName("w");w.setHusband(h);session.save(h);session.save(w);session.getTransaction().commit();session.close();}


原创粉丝点击