最近再学习Hibernate 的关联映射,在配置双向有连接表的一对一关联映射时遇到一些小麻烦,分享一下:
1.实体Student:
private int id;
private String name;
private int age;
private Address address;
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;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public Student() {
}
public Student(int age, String name) {
this.age = age;
this.name = name;
}
2.实体Address
public class Address {
private int addressId;
private String addressDetail;
private Student student;
public int getAddressId() {
return addressId;
}
public void setAddressId(int addressId) {
this.addressId = addressId;
}
public String getAddressDetail() {
return addressDetail;
}
public void setAddressDetail(String addressDetail) {
this.addressDetail = addressDetail;
}
public Address() {
}
public Address(String addressDetail) {
this.addressDetail = addressDetail;
}
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
配置文件:Student.hbm.xml
<class name="Student" table="STUDENT_TAB">
<id name="id" column="ID">
<generator class="identity"></generator>
</id>
<property name="age" type="int" column="AGE"/>
<property name="name" type="string" column="NAME"/>
<join table="student_addresss_tab" optional="true">
<key column="student_id" unique="true"/>
<many-to-one name="address" column="address_id" unique="true" not-null="true"/>
</join>
配置文件:Address.hbm.xml
<hibernate-mapping package="com.bluesky.hibernate.entity">
<class name="Address" table="ADDRESS_TAB">
<id name="addressId" column="ADDRESS_ID">
<generator class="identity"></generator>
</id>
<property name="addressDetail" type="string" column="ADDRESS_DETAIL"/>
<join table="student_addresss_tab" inverse="true" optional="true">
<key column="address_id" unique="true" />
<many-to-one name="student" column="student_id" unique="true" not-null="true"/>
</join>
</class>
</hibernate-mapping>
测试代码:
public class StudentAddress {
@SuppressWarnings("deprecation")
public static void execute() {
Configuration con = new Configuration().configure();
SessionFactory sf = con.buildSessionFactory();
Session session = sf.openSession();
Transaction tx = session.beginTransaction();
Address add1 = new Address("上海浦东");
session.persist(add1);
Student stu1 = new Student(18,"张三");
session.persist(stu1);
stu1.setAddress(add1);
add1.setStudent(stu1);
session.persist(add1);
session.persist(stu1);
tx.commit();
session.close();
sf.close();
}