Friday, 26 September 2014

Hibernate Mapping and Java Reflection API

Let's see one example to understand how hibernate using java reflection api.

We have one table EVENTS with three fields EVENT_ID, EVENT_DATE and TITLE.

For EVENTS table hibernate mapping file we define as follow.


<hibernate-mapping package="com.test.domain">
    <class name="Event" table="EVENTS">
        <id name="id" column="EVENT_ID">
            <generator class="native"/>
        </id>
        <property name="date" type="timestamp" column="EVENT_DATE"/>
        <property name="title"/>
    </class>
</hibernate-mapping>


Now first question is 'Why does the date property mapping include the column attribute, but the title does not ?'


Answer : Hibernate by default uses the property name as the column name. This works for title, however, date is a reserved keyword in most databases so you will need to map it to a different name.



Second question is  Why 'date' field having type attribute whereas 'title' field have not ?

Answer : Hibernate will try to determine the correct conversion and mapping type itself if the type attribute is not present in the mapping.  This automatic detection done using Java Reflection API. 

java.lang.reflect.Field class is there in Java api which having method called getType()


This is the case with the date property. Hibernate cannot know if the property, which is of java.util.Date, should map to a SQL date, timestamp, or time column. Full date and time information is preserved by mapping the property with a timestamp converter.


Keep In Mind : This Reflection process done when the mapping files are processed. This can take time and resources, so if startup performance is important you should consider explicitly defining the type to use.