Hibernate Example Using XML Mapping
Hibernate is an open-source Object Relational Mapping (ORM) framework used for mapping Java objects to relational database tables and vice versa. Using XML mapping in Hibernate refers to the process of defining the mapping between Java classes and database tables using XML configuration files instead of using annotations in the source code.
The XML mapping files in Hibernate are typically named as hibernate.cfg.xml
or hibernate.hbm.xml
, and they contain the mapping information for one or more classes. The XML mapping file specifies the database table name, column names, and their data types, as well as the relationships between tables such as one-to-one, one-to-many, and many-to-many. Here is an example of a Hibernate XML mapping file for Java class.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.dovale.okta.spring-hibernate</groupId>
<artifactId>raw-hibernate</artifactId>
<version>1.0-SNAPSHOT</version>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>8</source>
<target>8</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<hibernate-core-version>5.3.6.Final</hibernate-core-version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-core-version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.h2database/h2 -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
</dependencies>
</project>
package net.itcodescanner.entities;
import javax.persistence.*;
public class Employee {
private int id;
private String name;
private String address;
private Department department;
public Employee() {
}
public Employee( String name, String address, Department department) {
this.name = name;
this.address = address;
this.department = department;
}
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 String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
}
package net.itcodescanner.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
public class Department {
private int id;
private String name;
public Department() {
}
public Department(String name) {
this.name = name;
}
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;
}
}
package net.itcodescanner.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import javax.persistence.criteria.CriteriaQuery;
import java.util.List;
public abstract class AbstractCrudDao<T> {
private final SessionFactory sessionFactory;
private final Class<T> entityClass;
private final String entityName;
protected AbstractCrudDao(SessionFactory sessionFactory, Class<T> entityClass, String entityName) {
this.sessionFactory = sessionFactory;
this.entityClass = entityClass;
this.entityName = entityName;
}
public T save(T entity){
sessionFactory.getCurrentSession().save(entity);
return entity;
}
public void delete(T entity){
sessionFactory.getCurrentSession().delete(entity);
}
public T find(long id){
return sessionFactory.getCurrentSession().find(entityClass, id);
}
public List<T> list(){
Session session = sessionFactory.getCurrentSession();
CriteriaQuery<T> query = session.getCriteriaBuilder().createQuery(entityClass);
query.select(query.from(entityClass));
return session.createQuery(query).getResultList();
}
}
package net.itcodescanner.dao;
import net.itcodescanner.entities.Employee;
import org.hibernate.SessionFactory;
public class EmployeeDao extends AbstractCrudDao<Employee> {
public EmployeeDao(SessionFactory sessionFactory) {
super(sessionFactory, Employee.class, "Employee");
}
}
package net.itcodescanner.dao;
import org.hibernate.SessionFactory;
public class DepartmentDao extends AbstractCrudDao<net.itcodescanner.entities.Department> {
public DepartmentDao(SessionFactory sessionFactory) {
super(sessionFactory, net.itcodescanner.entities.Department.class, "Department");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:./data/db</property>
<property name="connection.username">sa</property>
<property name="connection.password"/>
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="employee.hbm.xml" />
<mapping resource="department.hbm.xml" />
</session-factory>
</hibernate-configuration>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="net.itcodescanner.entities.Employee" table="EMPLOYEE">
<id name="id" type="int">
<column name="EMPLOYEE_ID" />
<generator class="increment" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="address" type="java.lang.String">
<column name="ADDRESS" />
</property>
<many-to-one name="department" class="net.itcodescanner.entities.Department" fetch="select">
<column name="DEPARTMENT_ID" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"https://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="net.itcodescanner.entities.Department" table="DEPARTMENT">
<id name="id" type="int">
<column name="DEPARTMENT_ID" />
<generator class="increment" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
</class>
</hibernate-mapping>
package net.itcodescanner;
import net.itcodescanner.dao.*;
import net.itcodescanner.entities.*;
import org.hibernate.*;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class Application {
public static void main(String[] args){
StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try (SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory()) {
EmployeeDao employeeDAO = new EmployeeDao(sessionFactory);
DepartmentDao departmentDAO = new DepartmentDao(sessionFactory);
try (Session session = sessionFactory.getCurrentSession()) {
Transaction tx = session.beginTransaction();
// create departments
Department pj = departmentDAO.save(new Department("Department-21"));
Department px = departmentDAO.save(new Department("Department-22"));
employeeDAO.save(new Employee("EmpName-1", "Address-32", pj));
employeeDAO.save(new Employee("EmpName-2", "Address-54", px));
tx.commit();
}
try (Session session = sessionFactory.getCurrentSession()) {
session.beginTransaction();
System.out.println("Employees");
employeeDAO.list().forEach(employee -> System.out.println(employee.getId() +", " + employee.getName() + ", " + employee.getAddress() + ", " + employee.getDepartment().getName() ));
System.out.println("Departments");
departmentDAO.list().forEach(department -> System.out.println(department.getName() + ", " + department.getId()));
}
}
}
}
Hibernate: drop table DEPARTMENT if exists Hibernate: drop table EMPLOYEE if exists Hibernate: create table DEPARTMENT (DEPARTMENT_ID integer not null, NAME varchar(255), primary key (DEPARTMENT_ID)) Hibernate: create table EMPLOYEE (EMPLOYEE_ID integer not null, NAME varchar(255), ADDRESS varchar(255), DEPARTMENT_ID integer not null, primary key (EMPLOYEE_ID)) Hibernate: alter table EMPLOYEE add constraint FKfvt83ye0flecxfewcniue0n9n foreign key (DEPARTMENT_ID) references DEPARTMENT Aug 29, 2022 10:28:36 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@5f13be1] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode. Aug 29, 2022 10:28:36 AM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@73ab3aac] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode. Aug 29, 2022 10:28:36 AM org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@7573e12f' Hibernate: select max(DEPARTMENT_ID) from DEPARTMENT Hibernate: select max(EMPLOYEE_ID) from EMPLOYEE Hibernate: insert into DEPARTMENT (NAME, DEPARTMENT_ID) values (?, ?) Hibernate: insert into DEPARTMENT (NAME, DEPARTMENT_ID) values (?, ?) Hibernate: insert into EMPLOYEE (NAME, ADDRESS, DEPARTMENT_ID, EMPLOYEE_ID) values (?, ?, ?, ?) Hibernate: insert into EMPLOYEE (NAME, ADDRESS, DEPARTMENT_ID, EMPLOYEE_ID) values (?, ?, ?, ?) Employees Aug 29, 2022 10:28:36 AM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService INFO: HHH000397: Using ASTQueryTranslatorFactory Hibernate: select employee0_.EMPLOYEE_ID as EMPLOYEE1_1_, employee0_.NAME as NAME2_1_, employee0_.ADDRESS as ADDRESS3_1_, employee0_.DEPARTMENT_ID as DEPARTME4_1_ from EMPLOYEE employee0_ Hibernate: select department0_.DEPARTMENT_ID as DEPARTME1_0_0_, department0_.NAME as NAME2_0_0_ from DEPARTMENT department0_ where department0_.DEPARTMENT_ID=? 1, EmpName-1, Address-32, Department-21 Hibernate: select department0_.DEPARTMENT_ID as DEPARTME1_0_0_, department0_.NAME as NAME2_0_0_ from DEPARTMENT department0_ where department0_.DEPARTMENT_ID=? 2, EmpName-2, Address-54, Department-22 Departments Hibernate: select department0_.DEPARTMENT_ID as DEPARTME1_0_, department0_.NAME as NAME2_0_ from DEPARTMENT department0_ Department-21, 1 Department-22, 2 Aug 29, 2022 10:28:36 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop INFO: HHH10001008: Cleaning up connection pool [jdbc:h2:./data/db] Process finished with exit code 0
Leave a Comment