hibernate一对一(外键)

一.编写实体
@Entity
public class Wife {
	private int id;
	private String name;
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	public void setId(int id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}


@Entity
public class Husband {
	private int id;
	private String name;
	private Wife wife;
	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public String getName() {
		return name;
	}
	@OneToOne
	@JoinColumn(name="wifeId")
	public Wife getWife() {
		return wife;
	}
	public void setId(int id) {
		this.id = id;
	}
	public void setName(String name) {
		this.name = name;
	}
	public void setWife(Wife wife) {
		this.wife = wife;
	}
	
}


2.在hibernate.cfg.xml映射文件加上映射配置
 
<mapping class="org.hibernate.tutorial.domain.Husband"/>
		<mapping class="org.hibernate.tutorial.domain.Wife"/>


3.测试
public class OneToOneORMappingTest {
	public static void main(String[] args) {
		new SchemaExport(new AnnotationConfiguration().configure("/hibernate.cfg.xml")).create(true, false);
	}
}


注意:关联是在对象中加入另一个对象的引用,再加上@OneToOne
@JoinColumn(name="wifeId")注解。其中@JoinColumn表示设置当前对象在数据库的字段名
SchemaExport第一个参数,输出到控制台;第二个参数输出到数据库执行

-------------------------------------------------------------------
Object.cfg.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"> 

<hibernate-mapping package="org.hibernate.tutorial.domain"> 

    <class name="Event" table="EVENTS"> 
        <id name="id" column="EVENT_ID"> 
            <generator class="native"/> 
        </id> 
        <many-to-one name="Wife" clomn="wifeid" unique="true"></many-to-one>

    </class> 

</hibernate-mapping> 


在hibernate.cfg.xml设置引入映射, 
<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml"/>


unique:设置唯一性

你可能感兴趣的:(Hibernate)