Tuesday, July 13, 2010

Spring-Hibernate-CH-06

Value types

Persistent classes are called value types if they do not live independently in the application and are always represented without an identifier value.

The following simple rules identify value types:
  • They do not hold an identifier value.
  • They do not live independently in the application.
  • They are never shared between two or more persistent classes.

Entity types


Entity types, which live independently and are always identified with their identifier value. Phone and Student are examples of value type and entity type, respectively.


The following code shows an example of using the element, in which
the Student class and its composite field, Phone, are mapped to a single table:

Using XML

public class Student {
private Phone phone;
//other fields and getter/setter methods
}

public class Phone {
private String comment;
private String number;
//other fields and getter/setter methods
}



<hibernate-mapping>
<class name="com.packtpub.springhibernate.Student" table="STUDENT">
<id name="id" type="int" column="ID">
<generator class="increment"/>
</id>
<component name="phone" class="com.packtpub.springhibernate.Phone">
<property name="comment" column="COMMENT"/>
<property name="number" column="PHONE_NUMBER"/>
</component>
<!-- mapping of other fields -->
</class>
</hibernate-mapping>

Using Annotations

The @Embedded annotation is used to annotate a property to map as a component. Therefore, in our case, we would have the Student class as follows:

@Entity
@Table(name = "STUDENT")
public class Student {
@Embedded
private Phone phone;
//other fields and getter/setter methods
}


It is also possible to annotate the dependent class as a component with the @Embeddable annotation. Therefore, we don't need the @Embedded annotation anymore, and Hibernate always maps the object of the dependent class as a component. The following shows the Phone class annotated with @Embeddable:


@Embeddable
public class Phone {
private String comment;
@Column(name = "PHONE_NUMBER")
private String number;
//other fields and getter/setter methods
}

In the class above, we just marked the Phone class as a dependent component class. Therefore, all of Phone's properties will store to additional columns of the STUDENT table.



No comments:

Post a Comment