标签:
Husband类里有一个Wife类的引用
wife类:
package com.oracle.hibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Wife { private int id; private int age; @Id @GeneratedValue public int getId() { return id; } public void setId(int id) { this.id = id; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
Husband类:
package com.oracle.hibernate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinColumns; import javax.persistence.OneToOne; @Entity public class Husband { private int id; private String name; private Wife wife; //wife的引用 @Id //主键id @GeneratedValue //自动生成 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; } @OneToOne //一对一映射 //JoinColumn指定映射到表里哪个字段,不指定会自动生成的外键名为wife_id @JoinColumn(name="wifeId") public Wife getWife() { return wife; } public void setWife(Wife wife) { this.wife = wife; } }
hibernate.cfg.xml映射文件:
<mapping class="com.oracle.hibernate.Wife"/> <mapping class="com.oracle.hibernate.Husband"/>
junit测试类生成表的代码:
package com.oracle.hibernate; import org.hibernate.HibernateException; import org.hibernate.SessionFactory; import org.hibernate.cfg.AnnotationConfiguration; import org.hibernate.tool.hbm2ddl.SchemaExport; import org.junit.AfterClass; import org.junit.BeforeClass; public class Test { private static SessionFactory sf = null; @BeforeClass public static void beforeClass(){ try { sf = new AnnotationConfiguration().configure().buildSessionFactory(); } catch (HibernateException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @org.junit.Test public void testSchemaExport(){ new SchemaExport(new AnnotationConfiguration().configure()).create(false, true); } @AfterClass public static void afterClass(){ sf.close(); } }
生成的表:
hibernate生成表的语句:
create table Husband ( id integer not null auto_increment, name varchar(255), wifeId integer, primary key (id) ) 21:52:31,236 DEBUG SchemaExport:377 - create table Wife ( id integer not null auto_increment, age integer not null, primary key (id) ) 21:52:31,582 DEBUG SchemaExport:377 - alter table Husband add index FKAEEA401B796894FC (wifeId), add constraint FKAEEA401B796894FC foreign key (wifeId) references Wife (id)
可以看到,生成的husband表里外键wife名字已是wifeId
标签:
原文地址:http://www.cnblogs.com/lihaoyang/p/4915702.html