例子:
Husband.java
package com.bjsxt.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;
@Id
@GeneratedValue
public int getId() {
return id;
} public String getName() {
return name;
}
@OneToOne
@JoinColumns(
{
@JoinColumn(name="wifeId", referencedColumnName="id"), //设置字段名
@JoinColumn(name="wifeName", referencedColumnName="name")
}
)
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;
} }
Wife.java
package com.bjsxt.hibernate; import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass; @Entity
@IdClass(WifePK.class)
public class Wife {
private int id;
private String name;
private int age; public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Id
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} }
Wifepk.java
package com.bjsxt.hibernate; import java.io.Serializable; public class WifePK implements Serializable {
private int id;
private String name; 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;
} }
test
@Test
public void testSchemaExport() {
new SchemaExport(new AnnotationConfiguration().configure()).create(false, true);
}
总结