0

我用谷歌搜索,但所有示例都只向我展示了一对一Component的对象,例如:

https://dzone.com/tutorials/java/hibernate/hibernate-example/hibernate-mapping-component-using-annotations-1.html

我想要二合一Component的对象,例如:

public class PhoneNumber {
   // Phone details
   private int areaCode = 0;
   private int phoneNumber = 0;
   private String name = null;
}

public class Person {
   private String firstName = null;
   private String nickName = null;
   private String lastName = null;
   // Multiple phone details
   private PhoneNumber homePhone = null;
   private PhoneNumber mobilePhone = null;
}

休眠映射:

<class name="Person" table="PERSON">
 <id name="id" column="PERSON_ID">
  <generator class="native"/>
 </id>

 <property name="firstName" column="FIRST_NAME" />
 ...

 <component name="homePhone" class="PhoneNumber">
  <property name="areaCode" column="HOME_AREA_CODE"/>
  <property name="phoneNumber" column="HOME_PHONE_NUMBER"/>
  <property name="name" column="HOME_NAME"/>
 </component>

 <component name="mobilePhone" class="PhoneNumber">
  <property name="areaCode" column="MOBILE_AREA_CODE"/>
  <property name="phoneNumber" column="MOBILE_PHONE_NUMBER"/>
  <property name="name" column="MOBILE_NAME"/>
 </component>
</class>

Component上面有两个,homePhonemobilePhone。如何将上述Hibernate映射转换为Java注释?

4

1 回答 1

2
@Embeddable    
public class PhoneNumber {
 // Phone details
  private int areaCode = 0;
  private int phoneNumber = 0;
   private String name = null;
 }

 public class Person {
   private String firstName = null;
   private String nickName = null;
   private String lastName = null;
   // Multiple phone details
   @Embedded
   @AttributeOverrides({
   @AttributeOverride(name="areaCode",column=@Column(name="HOME_AREA_CODE"),
    @AttributeOverride(name="phoneNumber",column=@Column(name="HOME_PHONE_NUMBER"),
  @AttributeOverride(name="name",column=@Column(name="HOME_NAME")})
   private PhoneNumber homePhone = null;
  @Embedded
  @AttributeOverrides({
  @AttributeOverride(name="areaCode",column=@Column(name="MOBILE_AREA_CODE"),
  @AttributeOverride(name="phoneNumber",column=@Column(name="MOBILE_PHONE_NUMBER"),
  @AttributeOverride(name="name",column=@Column(name="MOBILE_NAME")})
   private PhoneNumber mobilePhone = null;
   }

使用 @Embeddable 注释您的电话类

对于每个电话组件,列名不同。使用@AttributeOverrride 并在您拥有的实体中指定适当的列名。这会将组件类映射到不同的列。

于 2016-07-06T08:34:09.627 回答