Search This Blog

Saturday, 10 September 2011

The mapping with minimum details

The mapping files are used to map the database table to the java object. For every such class, all the persistent properties have to be mapped. This is true in case of annotations too.
All Mapped classes must declare the primary key column of the database table. The <id> element defines the mapping from that property to the primary key column.
The typical property mapping includes the name of the property in the object, its type and corresponding column in the database.
I tried my hands at creating a minimalistic hbm file and use the hibernate defaults.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    <class name="com.other.domain.entity.DbPerson" table="PERSON">
        <id name="id">
            <generator class="native" />
        <property name="name" />
        <property name="date_of_birth" />

The <id> element cannot be omitted. For the id element, the name attribute however is also optional.If the name attribute is missing, it is assumed that the class has no identifier property.  
Also instead of <id> element the <composite-id> element can also be used.
The generator element is optional. Also its class attribute is optional if you are manually assigning the id value at the time of record creation or if you use the table for read purposes only.
For property element the type attribute is optional. If not specified then hibernate will use reflection to determine the mapping type to use. The name of the column also can be skipped as long as the property and the column have same names (case does not matter). Or a naming strategy is being used. In that case even the table name is optional for the class element.Thus the java class in this case has fields with names like date_of_birth and name. 
Hibernate also provides a <column> element that can be used instead of the column attribute.The <column> element is used when there are additional details to be provided , or more than one column is to be mapped to the same property.
The java class : 
package com.other.domain.entity;

import java.util.Date;

public class DbPerson {
    private Integer id;
    private String name;
    private Date date_of_birth;

   //setter getters


No comments:

Post a Comment