InterviewSolution
Saved Bookmarks
| 1. |
Explain identifiers in Hibernate? |
|
Answer» Derived properties are properties that are not mapped to any column of a database table. They are also known as calculated properties and are calculated at runtime. These properties are read-only in nature and can be defined using the @Formula annotation or by using the <formula> tag in the hbm.xml definition file. To use the @Formula annotation, we need to import org.hibernate.annotations.Formula package. Let us LOOK at an example. @Entity @Table(name="EMPLOYEE") public class Employee implements java.io.Serializable { @ID @Column(name="ID") private Integer id; @Column(name="FIRST_NAME", length=50) private String FIRSTNAME; @Column(name="LAST_NAME", length=50) private String lastName; @Column(name="MONTHLY_SALARY") private float monthlySalary; @Formula("MONTHLY_SALARY*12") private float yearlySalary; public Employee() { } public Integer getId() { RETURN id; } public void setId(Integer id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public float getMonthlySalary() { return monthlySalary; } public void setMonthlySalary(float monthlySalary) { this.monthlySalary = monthlySalary; } public float getYearlySalary() { return yearlySalary; } }In the above example, the @Formula annotation refers to the MONTHLY_SALARY column in the database table and not the monthlySalary property in the class. The hbm mapping for the above class would be: <?xml version="1.0"?> <!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.other.domain.entity.Employee" table="EMPLOYEE"> <id name="id" type="integer" access="property"unsaved-value="null"> <column name="ID"/> <generator class="native"/> </id> <property name="firstName" type="string" column="FIRST_NAME"/> <property name="lastName" type="string" column="LAST_NAME"/> <property name="monthlySalary" type="float" column="MONTHLY_SALARY"/> <property name="yearlySalary" type="float" column="YEARLY_SALARY" formula="(SELECT (MONTHLYSALARY*12) from EMPLOYEE e where e.id = ID)"/> </class> </hibernate-mapping> |
|