Hiberante学习10---基于Annotation配置的一对一双向外键关联

在单向外键关联中,我们是在student类中保存idcard的引用,这里在双向外键关联中是互相包含对方的引用,但这样子会造成对象不能保存,

所以要设置如下属性:

@OneToOne(mappedBy=stu)//设置将控制权交给哪一方?

双向关联,必须设置mappedBy属性,因为双向关联只能交给一方去控制,不可能在双方都设置外键保存关联关系,否则双方都无法保存。

 

步骤:

1、pojo类,这里我们将控制权交给Idcard类

package com.demo.pojo.sxwj;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;

@Entity
public class IdCard {

	private String pid;
	private String province;
	private Students stu;

	@OneToOne(cascade=CascadeType.ALL)
	@JoinColumn(name="sid")
	public Students getStu() {
		return stu;
	}
	public void setStu(Students stu) {
		this.stu = stu;
	}
	//不指定主键生成策略时,默认为GeneratedValue.AUTO
	@Id
	public String getPid() {
		return pid;
	}
	public void setPid(String pid) {
		this.pid = pid;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	
}


 

package com.demo.pojo.sxwj;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToOne;

@Entity
public class Students {
	private int sid;
	private String sname;
	private IdCard cardId;
	@Id
	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public String getSname() {
		return sname;
	}
	public void setSname(String sname) {
		this.sname = sname;
	}
	@OneToOne(mappedBy="stu")
	public IdCard getCardId() {
		return cardId;
	}
	public void setCardId(IdCard cardId) {
		this.cardId = cardId;
	}
	
}


 

2、配置文件没有变

3、测试类

package com.demo.pojo.sxwj;

import junit.framework.TestCase;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.tool.hbm2ddl.SchemaExport;

public class TestStudentByAnno extends TestCase{

	private SessionFactory sf;
	
	public void testSave()
	{
		sf = new AnnotationConfiguration().configure().buildSessionFactory();
		Session s = sf.getCurrentSession();
		Transaction tx = s.beginTransaction();
		tx.begin();
		
		Students student = new Students();
		student.setSname("zhangsan");
		
		IdCard idCard = new IdCard();
		idCard.setPid("11111111");
		idCard.setProvince("fujian");
		idCard.setStu(student);
		
		s.save(student);
		s.save(idCard);
		
		
		tx.commit();
	}

	public void testSchemaExport()
	{
		SchemaExport se = new SchemaExport(new AnnotationConfiguration().configure());
		se.create(true, true);
	}

	protected void setUp() throws Exception {
		System.out.println("setUp()....");
	}

	protected void tearDown() throws Exception {
		System.out.println("tearDown()....");
	}

	
	
}


 

 

 

你可能感兴趣的:(Hiberante学习10---基于Annotation配置的一对一双向外键关联)