Hibernate学习笔记_06_一对一单向外键关联

设置一对一的单向外键关联关系,通过Husband可以找到Wife,但是不能通过Wife找到Husband

1、编写实体类Wife;

       使用Annotation时,将实体类进行注解,@Entity 、@Id

package com.hibernate._0600_one2one_uni_fk;

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

@Entity
public class Wife {
	private Integer id;
	private String name;
	
	@Id
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}	
	
}

2、编写Husband类,并在Husband中添加Wife的引用 ;

package com.hibernate._0600_one2one_uni_fk;

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

/**单向一对一外间关联,*/
@Entity
public class Husband {
	private Integer id;
	private String name;
	private Wife wife;	  //去参考wife的id,此时wife必须先id

	@Id
	@GeneratedValue
	public Integer getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	@OneToOne    //设置关联关系
	@JoinColumn(name="wifeId")            //@JoinColumn 连接的字段,指定数据库中的名字,默认为wife_id
	public Wife getWife() {
		return wife;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setWife(Wife wife) {
		this.wife = wife;
	}
	
}

     在HUsband中添加Wife的引用,引用Wife的id ;

    使用Annotation时,将实体类进行注解,@Entity 、@Id;

    同时添加注解,设置关联关系为@OneToOne ;

    @JoinColumn注解可以设置外键在数据库中的字段名,也可以指定长度、类型等;


3、编写测试类,生成数据库表,查看表的关系;

public class ORMTest{
	private static SessionFactory sessionFactory;

	@BeforeClass
	public static void beforeClass() {
		sessionFactory = new AnnotationConfiguration().configure()
				.buildSessionFactory();
	}

	@AfterClass
	public static void afterClass() {
		sessionFactory.close();
	}
	@Test
	public void testSchemaExport() {
		new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
    }
}

4、在xml文件中,在class标签中加入
     <many-to-one name="wife" column="wifeId" unique="true"></many-to-one>

     unique="ture"  约束成一对一关联;


你可能感兴趣的:(Hibernate,数据库,String,测试,Integer,Class)