我只有名为Employee
的表名,该表具有所有地址属性,我想使用hibernate employee表和地址属性的内部类进行映射。
<property name="clientMark" column="CLIENT_MARK"/>
<property name="Address.street1" column="B_STREET_ADDRESS_1"/>
<property name="Address.street2" column="B_STREET_ADDRESS_2"/>
<property name="Address.city" column="B_CITY"/>
<property name="Address.state" column="B_STATE"/>
<property name="Address.postalCode" column="B_POSTAL_CODE"/>
<property name="Address.country" column="B_COUNTRY"/>
答案 0 :(得分:1)
如果我理解正确,你必须做这样的事情:
public class Employee {
private String clientMark;
private Address address;
public String getClientMark() {
return clientMark;
}
public void setClientMark(String clientMark) {
this.clientMark = clientMark;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public static class Address {
private String street1;
private String street2;
public String getStreet1() {
return street1;
}
public void setStreet1(String street1) {
this.street1 = street1;
}
public String getStreet2() {
return street2;
}
public void setStreet2(String street2) {
this.street2 = street2;
}
}
}
使内部类public和static能够从其他类创建新对象。然后为外部类中的内部类添加setter和getter方法,hibernate将能够设置并获取对象。接下来,您需要编辑.hbm.xml文件:
<property name="clientMark" column="CLIENT_MARK"/>
<component name="address">
<property name="street1" column="B_STREET_ADDRESS_1"/>
</component>
<component name="address">
<property name="street2" column="B_STREET_ADDRESS_2"/>
</component>
Hibernate注释<component>
表示命名变量将是包含一些变量的类(hbm.xml文件中为<property>
)。在此之后,您可以像这样测试您的代码:
Employee entity = new Employee();
entity.setClientMark("client_mark");
Employee.Address address = new Employee.Address();
address.setStreet1("street1");
address.setStreet2("street2");
entity.setAddress(address);
// entity is ready to be saved
您在数据库中的结果将是:
|------------------------------------------------------------|
| id | CLIENT_MARK | B_STREET_ADDRESS_1 | B_STREET_ADDRESS_2 |
|------------------------------------------------------------|
| 1 | client_mark | street1 | street2 |
|------------------------------------------------------------|
我希望它可以帮助你...☺