0% found this document useful (0 votes)
16 views

Hibernate Material (Part-II)

Hibernate

Uploaded by

Malavika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Hibernate Material (Part-II)

Hibernate

Uploaded by

Malavika
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

In the Hibernate mapping file we can do the following o-r mapping configurations.

i. Basic o-r mapping: Basic o-r mapping means mapping class with table, mapping
member variable with DB table columns.
ii. Component mapping: Component mapping one which to make component property
pointing multiple columns of DB table)
iii. Inheritance mapping: Inheritance mapping one which POJO classes are in
inheritance.
iv. Collection Mapping: I when Hibernate POJO class member variable type is Map or
List then we will go for this mapping.
v. Association Mapping: When POJO classes are there in the relationship like one-one,
one-to-many and etc.,)
i. Basic o-r mapping:

EX:
Class Jobtype
{
Double salary
String company;
String designation;
------------
------------
}
Pid, pname are simple properties because they are representing single column.
pid id(column)

pname name(column)

ii. Component mapping: The word represents component represents an object inside
another object representing multiple column values of Database table record.

Advantage: The advantage of this mapping is we can prepare separate java class object
representing the partial data of the record this gives possibility of sending the partial data of the
record as an object. So this is not that much important approach.

EX:

Class Jobtype

1
Double salary

String company;

String designation;

------------

-----------

iii. Pid, pname are simple properties because they are representing single column.
iv. pid id(column)
v.
vi. pname name(column)

Pjob is component property because represent columns.

vii. pjob sal, job columns.

P) Develop a Hibernate application by using Component Mapping.

For complete Program please refer Hibernate execution\Component Mapping folder

Inheritance mapping: Basic advantage of inheritance is extensibility that means we can prepare
new class based on the data and logics of existing class. Instead of developing Employee,
Student, Customer classes as separate individual concrete classes it is recommended to develop
them by extending them from common super class called Person. Hibernate persistence classes
are POJO classes and Java beans. So they can be designed participating in inheritance but we
must configure them in mapping file in Hibernate mapping file through inheritance mapping. To
make Hibernate software recognizing and utilizing the inheritance among the POJO classes when
Hibernate POJO classes are there in inheritance and they are configured as ordinary concrete
classes without using inheritance mapping then we need to configure child class direct properties
of super class configuration. If inheritance mapping is utilized we just need to configure child
class properties. Hibernate supports three types of the properties.

1. Table per class mapping


2. Table per subclass
3. Table per concrete class
1. Table per class mapping: In this mapping all the classes of inheritance hierarchy will be
single Database table.

2
i. In this strategy al the POJO classes of inheritance hierarchy will use single Database
table that means record in the table can be instead by using any POJO class of
inheritance hierarchy so there is a option to take discriminator column to keep track
of which record is inserted which POJO class of inheritance hierarchy.
ii. In this model the columns of table related to child POJO class properties can’t be take
applied with out not null constraint. This model of inheritance mapping not industry
standard because it makes us to take big tables having huge number of columns.
iii. In table per subclass inheritance mapping the super and sub classes will be
configured by using <class> <sub class> tags.

P) Develop a Hibernate application on Table per class mapping concept.

For complete Program please refer Hibernate execution\InheritenceMapping(Table per class)


folder

2. Table per subclass: Every class of inheritance hierarchy will use its own database table.
i. Table per subclass I popularly used model of inheritance mapping. In this model child
POJO class properties related columns of database table can be applied with not null
and other constraints.
ii. Every record inserted through Child POJO class will be inserted in both parent and
child tables having association between them. Here parent and Child POJO classes
must be configuring <class> <sub class> tag.
iii. Table per subclass mapping is industry standard to perform inheritance mapping
when Hibernate POJO classes are there in inheritance relationship.

P) Develop a Hibernate application on Table per sub class mapping concept.

For complete program please refer Hiberate execution\InheritenceMapping(Table per sub class)
folder

3. Table per concrete class: Every class of inheritance hierarchy will use its own database
table here the classes will be treated as concrete classes.
i. In this strategy even though Hibernate POJO classes are three in inheritance but they
will be treated as ordinary and concrete java classes while configuring them in
mapping file due to this while configuring each child POJO class the inherited
properties of parent class and direct properties of child class should be configured.
ii. In this strategy or model tables will be taken independent tables having concreted
columns one per class basis. Here every class of inherited hierarchy contains in our
database but classes will be configure in mapping file as concrete in mapping file as
concrete classes(inheritance won’t be utilized)

3
iii. This model is not industry recommended standard because mapping file leel the
inheritance between POJO classes won’t be used and tables will be created with
duplicate columns while working with this strategy.

P) Develop a Hibernate application on Table per concrete class mapping concept.

For complete program please refer Hiberate execution\InheriteceMapping(Table per Concrete


class) folder.

Implicit Polymorphism in Hibernate: In the above program Hibernate software used implicit
polymorphism.

Associative mapping:

Need of Association Mapping: Instead of designing large scale table having huge number of
columns it is recommended to design multiple tables and keep them in association or relationship
we can work with these multiple tables individually or together as needed this avoids duplicate
data in columns and also gives faster access to the data.

Association mapping supports <one-to-one>, <one-to-many>, <many-to-one>,<many-to-


many> tags. While designing Hibernate POJO classes for Association mappin we need to take
special properties of type collections. For this we need to configure these properties in mapping
file through collection mapping by using Set, Map, Bag and etc tags.

In hibernate two ways Association mapping is possible. Those ways are

i. Unidirectional Association Mapping(Parent to Child or Child to Parent mapping)


ii. Bidirectional Association mapping (Parent to child and child to parent)

Employee single table bad designing

Emo Enmae Sal Deptno Dept name


101 Raja 4000 1001 Accounts
102 Ravi 8000 1002 Sales
103 Raman 10000 1001 Accounts
406 Rakesh 7000 1002 Sales

Good Designing:

Employee( Parent table)

4
Eno Ename Sal Dept(fk with deptno)
101 Raja 9000 1001
102 Ravi 8000 1002
103 Raman 10000 1001
406 Rakesh 7000 1002

Dept(ChildTable):

Deptno DeptName
1001 Accoutns
1002 Sales

Here we can say Employee, dept tables are in one to one relationship. When Database tables are
in relationship/association we must also design their HB POJO classes supporting relationshipto
make Hibernate software recognizing the association between these HB POJO classes we must
configure them in mapping file through Association mapping. For this we need to use <one-to-
one>,<one-to-many>,<many-to-one>,<many-to-many> tags. While designing HB POJO classes
for Association mapping we need to take special properties of type collections for this we need to
configure these properties in mapping file through Collection mapping by using Set, Map, Bag
and etc tags. There are two ways of Association mapping in Hibernate.

i) Unidirectional mapping(Parent to child or child to parent)


ii) Bidirectional mapping(Parent to child and child to parent)

Parent to child mapping means each parent object can access one of more associated parent
objects.

Except many to many associations we can implement all other associations either in uni
directional mode but many to many implementation is always bi directional.

i) The association between students, Roll number details is one to one.


ii) The Association between persons and phone numbers.
iii) The association between Employees and departments is many to one.
iv) The association between students and faculties, doctors and patients is many to many.

P) Develop a Hibernate application on one to many unidirectional Association (parent –


child)

Please refer D:\Frameworks\Hiberate execution\one-to-many (Unidirectional) folder

User FirstName
101 Raja

5
102 Anil

Phone(pk) Number Type Unid


9999999999 Office 101
8888888888 Home 101
7777777777 Personal 101
6666666666 Office 102
5555555555 Home 102

To create table by keeping them in Associative use fk support.

P) Develop a Hibernate Program for one-to-Many Bidirectional Mapping.

For complete program please refer D:\Frameworks\Hiberate


execution\OnetoMany(Bidirectional)

i. Unidirectional Association Mapping (Parent to Child or Child to Parent


mapping): Parent to child mapping means parent object can access one or more
associated child associated child objects.
ii. Bi directional Association mapping (Parent to child and child to parent):

Child to parent mapping means each child objects can access one or more associated
parent objects.

One – to –one mapping: Student roll numbers

One-to-many mapping: Person – phone numbers

Many –to-many mapping: one doctor many patients or many patients one doctor

Note: unidirectional association mapping is not possible in many-to many mapping. It should
always in bidirectional.

Q) How can we develop Hibernate application without specifying mapping file in configuration
file?

A) cfg.addFile(“Employee.hbm.xml”)

Note: It is not industry recommended because we have to recompile client program each and
every time.

Q) What about lazy loading in Associative mapping?

6
A) In Associative mapping parent table records loads normally and child table records will load
on demand basis otherwise they will be selected normally by default lazy loading will be
enabled. While working with Associative mapping and collection mapping lazy loading will
enable automatically. We can set manually like this way <lazy=”true”>. This means Hibernate
software selects parent table records normal manner but associated child records on demand
basis. If we disable lazy loading child table records load along with parent table records.
Similarly Child POJO objects will be created and initialized along with parent POJO classes.

Note: In Association mapping to delete a record do not go for single row delete Hibernate
operation because it delete only parent record but not child so choose SQL or native SQL to
delete while working with Association mapping to delete main records and associated records. It
is recommended to write the logic of selecting and deleting records. If we try to delete the
records directly then the associated records may not be deleted.

Joins: In order to get data from two tables by having based on implicitly generated conditions
we need to work with JOINS.

Limitations of Hibernate Joins: To work with SQL level joins the two tables need to be there
in relationship. But to work with Hibernate joins the two tables must be in relationship.

HQL Supports the following types of JOINS.

i. Inner Join
ii. Left Outer Join(Left JOIN)
iii. Right Outer Join(Right Join)
iv. Full Join(not practically implemented)

To work with Joins we need to treat two tables as right side and left side.

1. Inner Joins: Inner joins gives the common data of both right side and left side tables.
2. Left Join: It gives the common data of both right side and left side tables. But
uncommon data it will give left side.
3. Right Join: It gives common data of both tables but uncommon data in right side.
4. Full Join: In Hibernate full pledged support is not given for full join that means
Hibernate software recognizes but there is no practical implementation for that keyword.

1+1 or n+1 select problem: While working with one-to-many or many-to-one association
mapping to select the records of the Hibernate software generate more queries this problem is
called n+1 problem.

EX: if User_table is having two records in phone_numbers table then Hibernate software
generates 2+1 select queries to select records. This is nothing but n+1 select problem. To

7
solve this problem and to reduce that select queries count to 1 we need to work with Fetch
keyword in HQL joins based query. Refer page no:89

Q) How many ways are to solve n+1 select problem?

A) While working with HQL Joins use Fetch keyword while working with Criteria API
speify the Fetch mode as Join.

EX: Criteria ct=ses.createCrietera(User.class)

Cf.setFetchMode(“phones”,FetchMode.JOIN);

Phones property in above specified paren POJO class(UserTable) pointing to Child


objects.

By using fetch=”join” in Hibernate mapping file.

<set name=”phones” table=”PHONE_NUMBERS” cascade=”all” fetch=”join”>

<key column=”UNID”/>

<one-to-many class=”PhoneNumber”/>

</set>

In Many-to-one Association:

<many-to-one name=”parent” class=”UserTable” column=”UNID” cascade=”all”


fetch=”join”>

For program please refer Hiberate execution\OnetoMany(Bidirectional) HQLJoinsTest


program.

One-to-one Association Mapping(Primary key): One-to-One Primary key association


mapping means it is Bidirectional Association mapping. Suppose any Parent POJO class object
contains one child object but child object is not ready to take parent object identity value at the
time we will go for this mapping.

P) Develop a Hibernate program on One-to-One Association Bidirectional Mapping?

For complete program please refer Hibernate execution\one-to-one (Primary Key)(Bi


Directional) folder.

One-to-One (Foreign Key) Association: one – to –one tag is not given for one-to-one foreign
key association it is given only for one-to-one Primary Key association due to this there is no

8
provision in one-to-one tag to specify foreign key column name so we use many – to –one tag
with unique=true, not-null=true attributes to perform foreign key based one-to-one association.
When parent, Child tables are designed by having unique constraint on foreign column then
tables will be there participating in one to one association. In the above statement then we can
achieve one-to-many or many-to-one association between parent and child.

P) Develop a Hibernate application one to one foreign key (unidirectional) association.

Please refer Hiberate execution\onetoonefk folder

Many-to-Many Association: It is always bi-directional association in implementation wise. In


this association third table support is required to make table1 and table2 recommends
participating in Association.

P) Develop a Hibernate application one many-to-many Association Mapping.

Please refer Hiberate execution\Many-to-Many folder

Collection Mapping: The Hiberante version List Data structure is nothing but bag Data
structure.

Bag Data Structure:

Org.hibernate.maopping.bag represents bag Data structure. The java.util.List or


org.hibernate.mapping.Bag type properties of Hibernate POJO classes configure by using <list>
<bag> in Hibernate mapping file. When Database table is having one column then we can take
predefined Java class like java.lang.String as Hibernate POJO class and we can use<element> in
mapping file to configure this class.

P) Develop a Hibernate application on bag Data Structure

Please refer Hibernate execution\Bag folder

Map Data Structure:

1. List, Set Data structures can store objects as elements but it does not allow us maintain
our choice indexes to those elements
2. Map Data structure elements contains keys and values. So we can add objects to Map
data structures with our choice indexing. In Association mapping if parent POJO class
contains Set, List type properties they can store Associative child objects but can’t
maintain their indexes o same parent class take Map type properties then it can maintain
the Associated child objects with indexes.

9
3. Map Type properties must be configured using <map> and specifying indexed columns.
This index column holds the keys placed in elements of Map Data structure. \

P) Develop a Hibernate application on Map Datastructure

Please refer Hiberate execution\Map folder

Q) How to Develop Hibernate application without specifying mapping file name in


Configuration File?

A) by using cfg.addFile(-)

EX: cfg.AddFile(“Employee.hbm.xml”)

Note:

1. While working with Association mapping and Collection mapping, lazy loading is
enabled means lazy=”true” the Hibernate software selects parent table record in a normal
manner but selects Associated Chile table records lazily on demand basis.
2. Here parent and child POJO class objects will also be created as their parent and child
table records are selected. By default all Associate mappings run with lazy loading.
3. In the above scenario when lazy loading is disabled child table records will be selected
along with parent table records. Similarly Child POJO objects will be created and
initialized along with parent POJO objects.

EX: <set name=”phones” cascade=”all” lazy=true/false”>

<key column=”UNID”/>

<one-to-many class =”Phone Number”/>

</set>

Note: In Associative mapping to delete record we should not go for single row delete
because Hibernate software delete only parent record but not Child record so We have to
choose Native SQL or HQL.

10

You might also like