Hibernate 双向一对一关联

本文只介绍实际开发中常用的设计模式(双向一对一关联)

其原理只是多对一的一种特例,只需增加一个unique="true"

下面看代码:

2个实体测试类:Man和Woman;理解为(一个男人可以娶一个女人,一个女人嫁一个男人)


package ray.one2one;

public class Man {
	private int id;
	private String name;
	private Woman woman;
	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 Woman getWoman() {
		return woman;
	}
	public void setWoman(Woman woman) {
		this.woman = woman;
	}
}

Woman类:

package ray.one2one;

public class Woman {
	private int id;
	private String name;
	private Man man;
	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 Man getMan() {
		return man;
	}
	public void setMan(Man man) {
		this.man = man;
	}
	
}
要点:Man和Woman各自维护一个引用对象,互相指向一个对象

再看配置文件:





	
		
			
		
		
		
		
		
	





	
		
			
		
		
		
		
	
最后看下测试类代码:
package ray.one2one;

import org.hibernate.Session;
import ray.SessionUtil.HibernateSessionFactory;

public class Test {
	public static void main(String[] args) {
		Woman woman = new Woman();
		woman.setName("文苹");
		Man man = new Man();
		man.setName("雷盼");
		man.setWoman(woman);
		woman.setMan(man);
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		
		session.save(woman);
		session.getTransaction().commit();
		session.close();
	}
}
输出结果:

Hibernate: 
    alter table _woman 
        add index FK_gxnyefreb964vdnbshbbmreou (m_id), 
        add constraint FK_gxnyefreb964vdnbshbbmreou 
        foreign key (m_id) 
        references _man (id)
Hibernate: 
    insert 
    into
        _man
        (name) 
    values
        (?)
Hibernate: 
    insert 
    into
        _woman
        (name, m_id) 
    values
        (?, ?)






你可能感兴趣的:(J2EE学习)