Nearby lessons

18 of 19

Hibernate - Different Types of Mappings

📌 What You Will Learn
  • Understand Hibernate - Different Types of Mappings
  • See working code examples
  • Learn from common mistakes and Q&A

Learn Hibernate - Different Types of Mappings step by step — simple explanations, complete programs with their output, common beginner mistakes, and exam-style MCQs.

Different Types of Mappings

  • List<Object[]> list = c.list();
  • System.out.println("ENO\tENAME\tESAL\tEADDR");
  • System.out.println("-------------------------------");
  • for(Object[] obj: list) {
  • for(Object o: obj) {
  • System.out.print(o+"\t");
  • System.out.println();
  • session.close();
  • sessionFactory.close();

Hibernate Filters

In Hibernate Applications, by using HQL queries, we are able to retrive multiple records of data from database table. While retriving multiple Records from Database table if we want to filter the results on the basis of a particular condition then we have to use "Hibernate Filters".

If we want to use Filters in Hibernate applications we have to use the following steps.

1)Prepare a table in Database with the required columns, where we must

define a filter parameter column

sql>create table emp(ENO number primary key, ENAME varchar2(10), ESAL float, EADDR varchar2(10), ETYPE varchar2(10));

Here "ETYPE" is Filter parameter column, by using this Filter parameter column only we are able to prepare Filter condition inorder to filter the results.

Define Filte in mapping File

To define Filter in mapping file we have to use the following xml tags in mapping file.

  • <hibernate-mapping>
  • <class name="--" table="--">
  • <filter name="--" condition="--"/>
  • </class>
  • <filter-def name="--">
  • <filter-param name="--" type="--"/>
  • </filter-def>
  • </hibernate-mapping>

 Where <filder-def> tag can be used to define a filter in Hibernate mapping file.  Where "name" attribute in <filter-def> tag is able to take logical name of the filter.  Where <filter-param> tag is a chaild tag to <filter-def> tag , it will define a particular filter

parameter.  Where "name" attribute in <filter-param" tag will take name of the filter parameter.  Where "type" attribute in <filter-param> tag will take java type like "string", "byte", "int",....

 Where "<filter>" tag under <class> tag is able to configure Filter to mapping.  Where "name" attribute in <filter> tag is able to take logical of the filter which we have

defined in <filter-def>" tag.  Where "condition" attribute in <filter> tag is able to define condition inorder to filter the

results. 3) Enable Filter in Session and set values to filter parameters inorder to filter

the results — Employee.java

To enable Filter in Session we have to use the following method from org.hibernate.Session. public Filter enableFilter(String logical_name)

To set values to the Filter parameter we will use the following method. public void setParameter(String filter_Name, xxx value) Where xxx may be byte, short, int,.....

To disable Filter , we will use the following method from org.hibernate.Session. public void disableFilter(String logical_Name)

Example:

Example05
JCode Cell
1 
2package com.durgasoft.pojo;
3public class Employee {
4private int eno;
5private String ename;
6private float esal;
7private String eaddr;
8private String etype;
9 
10public String getEtype() {
11return etype;
12}
13public void setEtype(String etype) {
14this.etype = etype;
15}
16public int getEno() {
17return eno;
18}
19public void setEno(int eno) {
20this.eno = eno;
21}
22public String getEname() {
23return ename;
24}
25public void setEname(String ename) {
26this.ename = ename;
27}
28public float getEsal() {
29return esal;
30}
31public void setEsal(float esal) {
32this.esal = esal;
33}
34public String getEaddr() {
35return eaddr;
36}
37public void setEaddr(String eaddr) {
38this.eaddr = eaddr;
39}
40 
41 
42}
43

the results — Employee.hbm.xml

Example06
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.pojo.Employee" table="emp2">
8 <id name="eno"/>
9 <property name="ename"/>
10 <property name="esal"/>
11<property name="eaddr"/>
12<property name="etype"/>
13<filter name="empFilter" condition=":type = ETYPE"/>
14</class>
15<filter-def name="empFilter">
16<filter-param name="type" type="string"/>
17</filter-def>
18</hibernate-mapping>
19

the results — hibernate.cfg.xml

Example07
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
10 <property name="connection.user">system</property>
11<property name="connection.password">durga</property>
12<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
13<property name="show_Sql">true</property>
14<mapping resource="Employee.hbm.xml"/>
15</session-factory>
16</hibernate-configuration>
17

the results — Test.java

Example08
JCode Cell
1 
2package com.durgasoft.test;
3 
4import java.util.List;
5import java.util.Scanner;
6 
7import org.hibernate.Filter;
8import org.hibernate.Query;
9import org.hibernate.Session;
10import org.hibernate.SessionFactory;
11import org.hibernate.boot.registry.StandardServiceRegistry;
12import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
13import org.hibernate.cfg.Configuration;
14 
15import com.durgasoft.pojo.Employee;
16 
17public class Test {
18 
19public static void main(String[] args){
20try {
21Configuration cfg = new Configuration();
22cfg.configure();
23StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
24builder = builder.applySettings(cfg.getProperties());
25StandardServiceRegistry registry = builder.build();
26SessionFactory sessionFactory = cfg.buildSessionFactory(registry);
27Session session = sessionFactory.openSession();
28 
29Query query = session.createQuery("from Employee");
30 
31Filter filter = session.enableFilter("empFilter");
32Scanner s = new Scanner(System.in);
33System.out.println("Employee Types:");
34System.out.println("1.PERM");
35System.out.println("2.TEMP");
36System.out.print("Your Option :");
37String etype = s.next();
38filter.setParameter("type", etype);
39List<Employee> list = query.list();
40 
41System.out.println("ENO\tENAME\tESAL\tEADDR\tETYPE");
42System.out.println("-----------------------------------------");
43for(Employee emp: list) {
44 System.out.println(emp.getEno()+"\t"+emp.getEname()+"\t"+emp.getEsal()+"\t"+emp.getEaddr()+"\t"+emp.getEtype());
45}
46session.close();
47sessionFactory.close();
48}catch(Exception e) {
49 e.printStackTrace();
50}
51}
52}
53

Hibernate Mappings

In Enterprise Applications, we are able to use the data models like Object Oriented Data Model, Relational Data Model,...In general, Front-End applications are able to use Object Oriented Data Model to represent data and Back-End Systems are able to use Relational Data Model to represent data.

In the above context, both Object Oriented Data Model and relational Data model are having their own conventions to represent data, these different conventions will create mismatches between data models, it will reduce data persistency in enterprise applications.

In the above context, to improve data persistency in enterprise applications we have to solve the mismatches between data models, for thos we have to use ORM implementations.

Hibernate is one of the ORM implementation , it has provided "Hibernate Mappings" feature to resolve mismatches between data models. To resolve mismatches between data models, Hibernate has provided the following mappings.

Different Types of Mappings

  • Basic OR Mapping.
  • Component Mapping
  • Inheritance Mapping
  • Association Mapping

Basic OR Mapping

It is normal mapping between a class, an ID property, a normal property from Object Oriented data model and a table, a primary key column and normal columns.

Component Mapping — Account.java

IN Hibernate applications, Component Mapping will provide solution for Granualarity Mismatch.

In Component mapping, we will define a component property inorder tyo refer multiple columns in a Database table.

To configure component property in hibernate applications we will use the following XML tags.

  • <hibernate-mapping>
  • <class name="--" table="--">
  • <component name="--" class="--">
  • </component>
  • </class>
  • </hibernate-mapping>

 Where "<component>" tag will take Component class and its reference variable declaration, where "name" attribute will take component property reference variable and "class" attribute will take fully qualified name of the respective component class.

Example:

Example12
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4public class Account {
5private String accNo;
6private String accName;
7private String accType;
8 
9public String getAccNo() {
10 return accNo;
11}
12public void setAccNo(String accNo) {
13this.accNo = accNo;
14}
15public String getAccName() {
16return accName;
17}
18public void setAccName(String accName) {
19this.accName = accName;
20}
21public String getAccType() {
22return accType;
23}
24public void setAccType(String accType) {
25this.accType = accType;
26}
27 
28 
29}
30

Component Mapping — Address.java

Example13
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4public class Address {
5private String pno;
6private String street;
7private String city;
8public String getPno() {
9 return pno;
10}
11public void setPno(String pno) {
12this.pno = pno;
13}
14public String getStreet() {
15return street;
16}
17public void setStreet(String street) {
18this.street = street;
19}
20public String getCity() {
21return city;
22}
23public void setCity(String city) {
24this.city = city;
25}
26 
27}
28

Component Mapping — Employee.java

Example14
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4public class Employee {
5private int eno;
6private String ename;
7private float esal;
8private Account eacc;
9private Address eaddr;
10 
11public int getEno() {
12return eno;
13}
14public void setEno(int eno) {
15this.eno = eno;
16}
17public String getEname() {
18return ename;
19}
20public void setEname(String ename) {
21this.ename = ename;
22}
23public float getEsal() {
24return esal;
25}
26public void setEsal(float esal) {
27this.esal = esal;
28}
29public Account getEacc() {
30return eacc;
31}
32public void setEacc(Account eacc) {
33this.eacc = eacc;
34}
35public Address getEaddr() {
36return eaddr;
37}
38public void setEaddr(Address eaddr) {
39this.eaddr = eaddr;
40}
41 
42}
43

Component Mapping — Employee.hbm.xml

Example15
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-mapping PUBLIC
4"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
6<hibernate-mapping>
7<class name="com.durgasoft.pojo.Employee" table="emp3">
8 <id name="eno"/>
9 <property name="ename"/>
10 <property name="esal"/>
11<component name="eacc" class="com.durgasoft.pojo.Account">
12 <property name="accNo"/>
13 <property name="accName"/>
14 <property name="accType"/>
15</component>
16<component name="eaddr" class="com.durgasoft.pojo.Address">
17 <property name="pno"/>
18 <property name="street"/>
19 <property name="city"/>
20</component>
21</class>
22</hibernate-mapping>
23

Component Mapping — hibernate.cfg.xml

Example16
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
10 <property name="connection.user">system</property>
11<property name="connection.password">durga</property>
12<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
13<property name="show_Sql">true</property>
14<mapping resource="Employee.hbm.xml"/>
15</session-factory>
16</hibernate-configuration>
17

Component Mapping — Test.java

Example17
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.hibernate.Transaction;
7import org.hibernate.boot.registry.StandardServiceRegistry;
8import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9import org.hibernate.cfg.Configuration;
10 
11import com.durgasoft.pojo.Account;
12import com.durgasoft.pojo.Address;
13import com.durgasoft.pojo.Employee;
14 
15public class Test {
16 
17public static void main(String[] args){
18SessionFactory sessionFactory = null;
19Session session = null;
20try {
21 Configuration cfg = new Configuration();
22 cfg.configure();
23 StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
24 builder = builder.applySettings(cfg.getProperties());
25 StandardServiceRegistry registry = builder.build();
26 sessionFactory = cfg.buildSessionFactory(registry);
27 session = sessionFactory.openSession();
28 
29 Account acc = new Account();
30 acc.setAccNo("a111");
31 acc.setAccName("AAA");
32 acc.setAccType("Savings");
33 
34 Address addr = new Address();
35 addr.setPno("23/3t");
36 addr.setStreet("MGRoad");
37 addr.setCity("Hyd");
38 
39 Employee emp = new Employee();
40 emp.setEno(111);
41 emp.setEname("AAA");
42 emp.setEsal(5000);
43 emp.setEacc(acc);
44 emp.setEaddr(addr);
45 
46 Transaction tx = session.beginTransaction();
47 session.save(emp);
48 tx.commit();
49 System.out.println("Employee Inserted Successfully");
50}catch(Exception e) {
51 e.printStackTrace();
52}finally {
53 session.close();
54 sessionFactory.close();
55 
56}
57}
58}
59

Component Mapping — Account.java

To provide component mapping in Hibernate applications we will use the following annotations from javax.persistence package.

@Embeddable @Embedded

 Where @Embeddable annotation will be used over the Component classs.  Where @Embedded annotation will be used over the component property.

Example:

Example18
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Embeddable;
6import javax.persistence.Entity;
7 
8@Entity
9@Embeddable
10public class Account {
11@Column(name="ACCNO")
12private String accNo;
13@Column(name="ACCNAME")
14private String accName;
15@Column(name="ACCTYPE")
16private String accType;
17 
18public String getAccNo() {
19return accNo;
20}
21public void setAccNo(String accNo) {
22this.accNo = accNo;
23}
24public String getAccName() {
25return accName;
26}
27public void setAccName(String accName) {
28this.accName = accName;
29}
30public String getAccType() {
31return accType;
32}
33public void setAccType(String accType) {
34this.accType = accType;
35}
36 
37 
38}
39

Component Mapping — Address.java

Example19
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Embeddable;
6import javax.persistence.Entity;
7 
8@Entity
9@Embeddable
10public class Address {
11@Column(name="PNO")
12private String pno;
13@Column(name="STREET")
14private String street;
15@Column(name="CITY")
16private String city;
17public String getPno() {
18return pno;
19}
20public void setPno(String pno) {
21this.pno = pno;
22}
23public String getStreet() {
24return street;
25}
26public void setStreet(String street) {
27this.street = street;
28}
29public String getCity() {
30return city;
31}
32public void setCity(String city) {
33this.city = city;
34}
35 
36 
37}
38

Component Mapping — Employee.java

Example20
JCode Cell
1 
2package com.durgasoft.pojo;
3 
4import javax.persistence.Column;
5import javax.persistence.Embedded;
6import javax.persistence.Entity;
7import javax.persistence.Id;
8import javax.persistence.Table;
9 
10@Entity
11@Table(name="emp3")
12public class Employee {
13@Id
14@Column(name="ENO")
15private int eno;
16@Column(name="ENAME")
17private String ename;
18@Column(name="ESAL")
19private float esal;
20@Embedded
21private Account eacc;
22@Embedded
23private Address eaddr;
24 
25public int getEno() {
26return eno;
27}
28public void setEno(int eno) {
29this.eno = eno;
30}
31public String getEname() {
32return ename;
33}
34public void setEname(String ename) {
35this.ename = ename;
36}
37public float getEsal() {
38return esal;
39}
40public void setEsal(float esal) {
41this.esal = esal;
42}
43public Account getEacc() {
44return eacc;
45}
46public void setEacc(Account eacc) {
47this.eacc = eacc;
48}
49public Address getEaddr() {
50return eaddr;
51}
52public void setEaddr(Address eaddr) {
53this.eaddr = eaddr;
54}
55 
56 
57}
58

Component Mapping — hibernate.cfg.xml

Example21
JCode Cell
1 
2<?xml version="1.0" encoding="UTF-8"?>
3<!DOCTYPE hibernate-configuration PUBLIC
4"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
5"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
6<hibernate-configuration>
7<session-factory>
8 <property name="connection.driver_Class">oracle.jdbc.OracleDriver</property>
9 <property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
10 <property name="connection.user">system</property>
11<property name="connection.password">durga</property>
12<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
13<property name="show_Sql">true</property>
14<mapping class="com.durgasoft.pojo.Employee"/>
15</session-factory>
16</hibernate-configuration>
17

Component Mapping — Test.Java

Example22
JCode Cell
1 
2package com.durgasoft.test;
3 
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;
6import org.hibernate.Transaction;
7import org.hibernate.boot.registry.StandardServiceRegistry;
8import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
9import org.hibernate.cfg.Configuration;
10 
11import com.durgasoft.pojo.Account;
12import com.durgasoft.pojo.Address;
13import com.durgasoft.pojo.Employee;
14 
15public class Test {
16 
17public static void main(String[] args){
18SessionFactory sessionFactory = null;
19Session session = null;
20try {
21 Configuration cfg = new Configuration();
22 cfg.configure();
23 StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();
24 builder = builder.applySettings(cfg.getProperties());
25 StandardServiceRegistry registry = builder.build();
26 sessionFactory = cfg.buildSessionFactory(registry);
27 session = sessionFactory.openSession();
28 
29 Employee emp = (Employee)session.get(com.durgasoft.pojo.Employee.class, 111);
30 System.out.println("Employee Details");
31 System.out.println("------------------------");
32 System.out.println("Employee Number :"+emp.getEno());
33 System.out.println("Employee Name :"+emp.getEname());
34 System.out.println("Employee Salary :"+emp.getEsal());
35 System.out.println();
36 Account acc = emp.getEacc();
37 System.out.println("Account Details");
38 System.out.println("-------------------");
39 System.out.println("Account Number :"+acc.getAccNo());
40 System.out.println("Account Name :"+acc.getAccName());
41 System.out.println("Account Type :"+acc.getAccType());
42 System.out.println();
43 Address addr = emp.getEaddr();
44 System.out.println("Address Details");
45 System.out.println("--------------------");
46 System.out.println("PNO :"+addr.getPno());
47 System.out.println("Street :"+addr.getStreet());
48 System.out.println("City :"+addr.getCity());
49}catch(Exception e) {
50 e.printStackTrace();
51}finally {
52 session.close();
53 sessionFactory.close();
54 
55}
56}
57}
58

Inheritance Mapping — Account.java

In Enterprise Applications, we are able to use the data models like Object Oriented Data Model, Relational Data Model,...In general, Front-End applications are able to use Object Oriented Data Model to represent data and Back-End Systems are able to use Relational Data Model to represent data. In Object Oriented Data Model, we will provide inheritance relation between entities inorder to improve code Reusability.

In Relational data Model, we will use different approaches to manage inheritance kind of features at databases like maintaining all the classes properties in a single table or defining a seperate table for each and every class and providing PK-FK relation between these tables,.....

In both the above cases, approaches are different to achive inheritance kind of feature, it will provide Sub types mismatches between data models, it will reduce data persistencey in enterprise applications.

In the above context, to improve data persistency in enterprise applications we have to use ORM implementation, Hibernate is one of the ORM implementation, it has provided the following three strategies to resolve inheritance mismatch.

  • Table Per Class Hierarchy.
  • Table Per Sub Class
  • Table Per Concreate Class

1) Table Per Class Hierarchy. In Table Per Class hierarchy, we will prepare a table with the columns representing all the properties of the classes[sub classes and super class] which are existed in inheritance.

In this mechanism, when we store any sub class object then data must be stored in single table in the respective columns, if data is not available for any column then null values will be stored in the respective columns.

If we want to use Table Per Class Hierarchy in Hibernate applications then we have to use the following steps. 1) Prepare all java classes which we want to keep in Inheritance

EX:

Example23
JCode Cell
1 
2public class Account {
3private String accNo;
4private String accName;
5private String accType;
6 setXXX() and getXXX()
7}
8

Inheritance Mapping — StudentAccount.java

Example24
JCode Cell
1 
2public class StudentAccount extends Account{
3private String sid;
4private String sbranch;
5private int smarks;
6 setXXX() and getXXX()
7}
8

Inheritance Mapping — EmployeeAccount.java

Example25
JCode Cell
1 
2public class EmployeeAccount extends Account{
3private String eid;
4private float esal;
5private String eaddr;
6 setXXX() and getXXX()
7}
8

Inheritance Mapping

2) Create a table in Database with a set of columns which are representinig all properties of

the classes which are existed in inheritance and discriminator column

SQL> create table account(ACCNO varchar2(5) primary key, ACCNAME varchar2(5), accType varchar2(10), SID varchar2(5), SBRANCH varchar2(5), SMARKS number(3), EID varchar2(5), ESAL float, EADDR varchar2(10), TYPE varchar2(10));

Where the purponse Discriminator column is to specify which sub class object data is represented by the present record.

3) Provide all subclasses configuration and discriminator column configuration in

hibernate mapping file by using the following tags

  • <hibernate-mapping>
  • <class name="--" class="--">
  • <discrimantor column="--"/>
  • <subclass name="--" discriminator-value="--">
  • </subclass>
  • </class>
  • </hibernate-mapping>

 Where "<discriminator>" tag can be used to configure discriminator column, where

"column" attribute in <discriminator> tag will take the discriminator column name which we defined in database table.

 Where "<subclass> tag is able to configure a single sub class and its properties, where "name" attribute will take fully qualified name of the respective sub class, where "discriminator-value" attribute will provide the exact discriminator value inorder to insert or retrive sub class object data.

Example28
JCode Cell
1 
2<hibernate-mapping>
3<class name="com.durgasoft.pojo.Account" table="account">
4 <id name="accNo" column="ACCNO"/>
5 <discriminator column="TYPE" type="string"/>
6 <property name="accName" column="ACCNAME"/>
7 <property name="accType" column="ACCTYPE"/>
8 
9 <subclass name="com.durgasoft.pojo.StudentAccount" discriminator-value="std">
10 <property name="sid" column="SID"/>
11 <property name="sbranch" column="SBRANCH"/>
12 <property name="smarks" column="SMARKS"/>
13</subclass>
14 
15<subclass name="com.durgasoft.pojo.EmployeeAccount" discriminator-value="emp">
16 <property name="eid" column="EID"/>
17 <property name="esal" column="ESAL"/>
18 <property name="eaddr" column="EADDR"/>
19</subclass>
20</class>
21</hibernate-mapping>
22

hibernate mapping file by using the following tags

4) In client application, Create Sub class objects with the data and perform the required

database operation

  • SessionFactory factory = cfg.buildSessionFactory(registry);
  • Session session = factory.openSession();
  • StudentAccount sa = new StudentAccount();
  • sa.setAccNo("a1");
  • sa.setAccName("AAA");
  • sa.setAccType("Savings");
  • sa.setSid("S1");
📝 Key Takeaways
  • Key ideas of Hibernate - Different Types of Mappings explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end