An Object/relational mappings are usually defined in an XML document. This mapping file instructs Hibernate how to map the defined class or classes to the database tables.
Though many Hibernate users choose to write the XML by hand, a number of tools exist to generate the mapping document. These include XDoclet, Middlegen and AndroMDA for advanced Hibernate users. Let us consider our previously defined POJO class whose objects will persist in the table defined in next section.
publicclassEmployee{
privateint id; privateString firstName; privateString lastName; privateint salary; publicEmployee(){} publicEmployee(String fname,String lname,int salary){ this.firstName = fname; this.lastName = lname; this.salary = salary; } publicint getId(){ return id; } publicvoid setId(int id ){ this.id = id; } publicString getFirstName(){ return firstName; } publicvoid setFirstName(String first_name ){ this.firstName = first_name; } publicString getLastName(){ return lastName; } publicvoid setLastName(String last_name ){ this.lastName = last_name; } publicint getSalary(){ return salary; } publicvoid setSalary(int salary ){ this.salary = salary; } } There would be one table corresponding to each object you are willing to provide persistence. Consider above objects need to be stored and retrieved into the following RDBMS table:
create table EMPLOYEE (
id INT NOT NULL auto_increment, first_name VARCHAR(20)default NULL, last_name VARCHAR(20)default NULL, salary INT default NULL, PRIMARY KEY (id) ); Based on the two above entities we can define following mapping file which instructs Hibernate how to map the defined class or classes to the database tables.
<?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> <classname="Employee"table="EMPLOYEE"> <metaattribute="class-description"> This class contains the employee detail. </meta> <idname="id"type="int"column="id"> <generatorclass="native"/> </id> <propertyname="firstName"column="first_name"type="string"/> <propertyname="lastName"column="last_name"type="string"/> <propertyname="salary"column="salary"type="int"/> </class> </hibernate-mapping> You should save the mapping document in a file with the format
|