Hibernate Component Mapping using XML
Previously we have learned about Component Mapping in Hibernate using Annotations. In this example, we will learn about Hibernate Component Mapping using XML. In our example, we have two classes Employee and EmployeeAddress. The Employee can have an Address but Address cannot exist separately without Employee. Since the Employee and Address entities are strongly related, it is better to store them in a single table using component mapping( tag).
Creating table
Create EMPLOYEE Table, simply Copy and Paste the following SQL query in the query editor to get the table created.
CREATE TABLE "EMPLOYEE" ( "EMP_ID" NUMBER(10,0) NOT NULL ENABLE, "EMP_NAME" VARCHAR2(255 CHAR), "DEPARTMENT" VARCHAR2(255 CHAR), "STREET" VARCHAR2(255 CHAR), "CITY" VARCHAR2(255 CHAR), "STATE" VARCHAR2(255 CHAR), PRIMARY KEY(EMP_ID) );
Folder Structure:
- Create a simple MavenProject“HibernateTutorial” and create a package for our source files “com.javainterviewpoint” under src/main/java
- Now add the following dependency in the POM.xml
4.0.0 HibernateTutorial HibernateTutorial 0.0.1-SNAPSHOT 4.3.11.Final 11.2.0 org.hibernate hibernate-core $ com.oracle ojdbc14 $ src maven-compiler-plugin 3.3 1.7
Other interesting articles which you may like …
- Hibernate Hello World Example in Eclipse (XML Mapping)
- Hibernate Hello World Example in Eclipse (Annotation)
- Hibernate One To One Bidirectional Mapping XML Example with Primary Key
- Hibernate One To One Mapping XML Example with Foreign Key
- Hibernate One To Many Mapping XML Example
- Hibernate Many To Many Mapping Example – XML Mapping
- Hibernate One To One Bidirectional Mapping – Primary Key(Annotation)
- Hibernate One To One Bidirectional Mapping Example – Foreign Key(Annotation)
- Hibernate One To Many Mapping Example Using Annotation
- Hibernate Many To Many Mapping Example – Annotation
- Hibernate CRUD Example in Eclipse (XML Mapping) with Maven + Oracle
- Hibernate Inheritance – Table Per Class Hierarchy (XML Mapping & Annotation)
- Hibernate Inheritance – Table Per Subclass Hierarchy (XML Mapping & Annotation)
- Hibernate Inheritance – Table Per Concrete Class Hierarchy Example(XML Mapping & Annotation)
- Hibernate Composite Primary Key Tutorial – Using composite-id tag & Annotations
- Hibernate Embeddable Composite Primary Key | @Embeddable, @EmbeddedId
- Difference between session.get() and session.load() in Hibernate
Hibernate Component Mapping using XML
EmployeeAddress.java
package com.javainterviewpoint; import java.io.Serializable; public class EmployeeAddress implements Serializable < private static final long serialVersionUID = 1L; private String street; private String city; private String state; public EmployeeAddress() < super(); >public EmployeeAddress(String street, String city, String state) < super(); this.street = street; this.city = city; this.state = state; >public String getStreet() < return street; >public void setStreet(String street) < this.street = street; >public String getCity() < return city; >public void setCity(String city) < this.city = city; >public String getState() < return state; >public void setState(String state) < this.state = state; >@Override public String toString() < return "Employee_Address [street=" + street + ", city=" + city + ", state=" + state + "]"; >>
Our EmployeeAddress class is a simple POJO class consisting of the getters and setters for the EmployeeAddress class properties (street, city, state).
Employee.java
package com.javainterviewpoint; import java.io.Serializable; public class Employee implements Serializable < private static final long serialVersionUID = 1L; private int id; private String name; private EmployeeAddress employeeAddress; public Employee() < super(); >public Employee(int id, String name, EmployeeAddress employeeAddress) < super(); this.id = id; this.name = name; this.employeeAddress = employeeAddress; >public int getId() < return id; >public void setId(int id) < this.id = id; >public String getName() < return name; >public void setName(String name) < this.name = name; >public EmployeeAddress getEmployeeAddress() < return employeeAddress; >public void setEmployeeAddress(EmployeeAddress employeeAddress) < this.employeeAddress = employeeAddress; >@Override public String toString() < return "Employee [id=" + id + ", name=" + name + ", employeeAddress=" + employeeAddress + "]"; >>
Our Employee class is a simple POJO class consisting of the getters and setters for the Employee class properties (id, name, employeeAddress).
employee.hbm.xml
- The “employee.hbm.xml” tells hibernate to map “Employee” and “EmployeeAddress” class with the “EMPLOYEE” table in the database.
- We have a new tag tag added which lets us add a component mapping in hibernate.
- tag maps the property of both Employee and EmployeeAddress to the corresponding column in EMPOYEE table.
hibernate.cfg.xml
Place the hibernate.cfg.xml file also under the src/main/resources folder
oracle.jdbc.driver.OracleDriver root root jdbc:oracle:thin:@mydb:40051:dev 1 org.hibernate.dialect.Oracle10gDialect true update
- First and foremost property is for specifying the JDBC Driver class, in my case it OracleDriver
oracle.jdbc.driver.OracleDriver
- Give the connection URL for connecting the database and provide username and password for connecting the above database
jdbc:oracle:thin:@mydb:40051:dev root root
- Specify the connection pool size, this property limits the number of connections in the Hibernate connection pool.
- Dialect Property makes the Hibernate generate the SQL for the corresponding database which is being used. In this example we are using Oracle database hence Oracle query will be generated. If you are using MySQL database then you need to change the dialect accordingly.
org.hibernate.dialect.Oracle10gDialect
- The show_sql property will print the executed sql in the console when set to true.
- If the property “hibernate.hbm2ddl.auto” is set to “create” This will drop and recreate the database schema on every execution. If it is set to “update” then the database schema will be updated every time rather than dropping and recreating.
- Under the Mapping resource tag, we need to specify all the mapping resources for which we need the table to be created or updated.
ComponentMapping.java
package com.javainterviewpoint; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import org.hibernate.service.ServiceRegistry; public class ComponentMapping < public static void main(String args[]) < //Reading the hibernate configuration file Configuration configuration = new Configuration().configure("hibernate.cfg.xml"); StandardServiceRegistryBuilder regBuilber = new StandardServiceRegistryBuilder(); regBuilber.applySettings(configuration.getProperties()); ServiceRegistry serviceRegistry = regBuilber.build(); //Create SessionFacctory SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry); //Create Session from SessionFactory Session session = sessionFactory.openSession(); //Begin the transaction session.beginTransaction(); //Create a new EmployeeAddress object EmployeeAddress address = new EmployeeAddress(); address.setStreet("Tharamani"); address.setCity("Chennai"); address.setState("TamilNadu"); //Create a new Employee object Employee employee = new Employee(); //employee.setId(1); employee.setName("JavaInterviewPoint"); employee.setAddress(address); session.save(employee); //Commit the changes session.getTransaction().commit(); //Close the session session.close(); >>
- Create the Configuration object and read the configuration file using the configure() method.
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
- Get the SessionFactory object through the buildSessionFactory() method of the configuration object.
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
- openSession() method opens up the new session and begin a new transaction
Session session = sessionFactory.openSession(); session.beginTransaction();
- Create EmployeeAddress and Employee object and set values to its properties
//Create a new EmployeeAddress object EmployeeAddress address = new EmployeeAddress(); address.setStreet("Tharamani"); address.setCity("Chennai"); address.setState("TamilNadu"); //Create a new Employee object Employee employee = new Employee(); //employee.setId(1); employee.setName("JavaInterviewPoint"); employee.setAddress(address);
- save() method of the session object will persist the Employee object
- Finally get the transaction and commit the changes and close the session.
session.getTransaction().commit(); session.close();
INFO: HHH000261: Table found: EMPLOYEE Apr 05, 2017 5:48:54 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000037: Columns: [emp_name, street, emp_id, state, city] Apr 05, 2017 5:48:54 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000108: Foreign keys: [] Apr 05, 2017 5:48:54 PM org.hibernate.tool.hbm2ddl.TableMetadata INFO: HHH000126: Indexes: [sys_c0015424] Apr 05, 2017 5:48:54 PM org.hibernate.tool.hbm2ddl.SchemaUpdate execute INFO: HHH000232: Schema update complete Hibernate: select hibernate_sequence.nextval from dual Hibernate: insert into EMPLOYEE (EMP_NAME, STREET, CITY, STATE, EMP_ID) values (?, ?, ?, ?, ?)
Leave a Reply Cancel reply
This site uses Akismet to reduce spam. Learn how your comment data is processed.
Hibernate hbm.xml
In hibernate, there is two way of mapping — first one is by using hibernate annotation and second one is by using hbm.xml.
When you use hbm.xml, just modify default hibernate SessionFactory class in hibernate-cfg.xml by passing your «hbm.xml» file path as an argument to resource method.
Example: Here we are taking an example of employee table.
Employee.hbm.xml file is your hbm.xml file in which table column and their types are mapped.
Employee.hbm.xml
hibernate-cfg.xml is configuration file of hibernate where you map hbm.xml
com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/hibernate root root 1 org.hibernate.dialect.MySQLDialect thread org.hibernate.cache.NoCacheProvider true none
Tutorials
- Why hibernate is used?
- Hibernate Native SQL Example
- Hibernate Update Query
- Hibernate Delete Query
- Hibernate Count Query
- Writing First Hibernate Code
- Running First Hibernate 3.0 Example
- Hibernate Book
- Understanding Hibernate O/R Mapping
- Using Hibernate to generate id incrementally
- Hibernate Query Language
- Preparing table for HQL Examples
- Writing ORM for Insurance table
- HQL from clause Example
- Hibernate Select Clause
- HQL Where Clause Example
- Hibernate Architecture
- HQL Group By Clause Example
- hibernateTemplate-Order Results
- Hibernate Criteria Query Example
- Hibernate How To
- Hibernate Quickly
- Hibernate 3.1.2 Released
- HQL Order By Example
- Hibernate 3.1.3 Released
- Hibernate 3.1.1 Released
- Introduction to Hibernate 3.0
- Complete Hibernate 3.0 and Hibernate 4 Tutorial
- Hibernate Avg() Function (Aggregate Functions)
- Hibernate Max() Function (Aggregate Functions)
- Hibernate Min() Function (Aggregate Functions)
- Hibernate Criteria Expression (eq)
- Hibernate Criteria Expression (lt)
- Hibernate Criteria Expression (le)
- Hibernate Criteria Expression (gt)
- Hibernate Criteria Expression (ge)
- Hibernate Criteria Expression (and)
- Hibernate Criteria Expression (or)
- Hibernate Projections (rowCount or countDistinct)
- Hibernate Projection Count