如何在注释中使用多种组件类型(嵌入式、可嵌入)

How to use more than one Component type (Embedded, Embeddable) in annotation

我google,但所有示例只显示一个对象中的一个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>

我上面有两个ComponenthomePhonemobilePhone。如何将上面的 Hibernate 映射翻译成 Java 注释?

@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

注释你Phoneclass

对于每个 phone 组件,列名不同。使用 @AttributeOverrride 并指定适当的列名称,因为 entity.This 会将组件 class 映射到不同的列。