Hibernate Mapping using xml
A mapping file in Hibernate is used to map the fields of a java class with the fields of the table in a relational database.
Let's follow the below steps.
CREATE A JAVA CLASS
Let us create a class named 'Employee' in java :
class Employee{
int empId;
String name;
---Getters & Setters---
}
CREATE A TABLE IN THE DATABASE
Similarly in the database let us create a table named EMPLOYEE :
CREATE TABLE EMPLOYEE (EMP_ID INTEGER, NAME VARCHAR, PRIMARY KEY (ID));
CREATE THE MAPPING FILE
Now, the mapping file would look like:
Employee.hbm.xml
<?xml version = "1.0" encoding = "utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name = "Employee" table = "EMPLOYEE">
<id name = "empId" type = "int">
<column name = "EMP_ID">
</id>
<property name = "name" type = "string">
<column name = "NAME">
</property>
</class>
</hibernate-mapping>
The above mapping file says, to which table the java class will map to.
<class name = "Employee" table = "EMPLOYEE">
In the above case the Employee class is getting mapped to EMPLOYEE table.
<id name = "empId" type = "int">
<column name = "EMP_ID">
</id>
The <id> tag specifies the primary key, where we have linked the class attribute (i.e. empId) with the column name (i.e. EMP_ID) of the EMPLOYEE table.
<property name = "name" type = "string">
<column name = "NAME">
</property>
Finally, we have the <property> tag where we have linked the class attribute (i.e. name) with the column name (i.e. NAME).
Mapping can also be achieved using Annotations, which we will be looking later.