|
Mapping files are the heart of O/R mapping tools. These are the files that contain field to field mapping between the class attributes and the database columns. Let's write a mapping file for the User class that we want to persist to the database.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" > <hibernate-mapping> <class name="com.visualbuilder.hibernate.User" table="USERS" > <id name="userId" type="java.lang.Long" column="user_id" > <generator class="increment" /> </id> <property name="firstName" type="java.lang.String" column="first_name" length="20" /> <property name="lastName" type="java.lang.String" column="last_name" length="20" /> <property name="age" type="java.lang.Integer" column="age" length="-1" /> <property name="email" type="java.lang.String" column="email" length="40" /> </class> </hibernate-mapping>
As you can see,we have mapped all of the attributes of the class "User" to the columns of the table we created previously. Note the "id" attribute which maps the userId field of class User is defined in a different way than the other properties. The id tag is used to indicate that this is a primary key,and a <generator> tag is used to generate the primary key using different techniques. We have used the increment class,but there are also available different classes to support different kind of key generation techniques like generating key from a sequence,selecting from database etc. We can also use a custom key generator class.
Let us now add the mapping file to the Hibernate configuration file hibernate.cfg.xml. After adding the mapping resource entry,the hibernate.cfg.xml looks like this.
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:oracle:thin:@localhost:1521:XE</property> <property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property> <property name="connection.username">SYSTEM</property> <property name="connection.password">manager</property>
<!-- Set AutoCommit to true --> <property name="connection.autocommit">true</property>
<!-- SQL Dialect to use. Dialects are database specific --> <property name="dialect">net.sf.hibernate.dialect.OracleDialect</property> <!-- Mapping files --> <mapping resource="com/visualbuilder/hibernate/User.hbm.xml" /> </session-factory> </hibernate-configuration> |