SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Downloaden Sie, um offline zu lesen
© People Strategists www.peoplestrategists.com Slide 1 of 45
Hibernate Day 1
© People Strategists www.peoplestrategists.com Slide 2 of 45
In this session, you will learn to:
Explore the basics of hibernate
Explore the hibernate framework
Configure mapping properties
Objectives
© People Strategists www.peoplestrategists.com Slide 3 of 45
Java Database Connectivity (JDBC):
Is a standard Java API for database-independent connectivity between the
Java programming language and a wide range of databases.
Provides a complete set of interfaces that allows for portable access to an
underlying database.
Provides the same capabilities as ODBC, allowing Java programs to contain
database-independent code.
Library includes APIs for the following tasks that are commonly associated
with database usage:
 Making a connection to a database.
 Creating SQL or MySQL statements.
 Executing SQL or MySQL queries in the database.
 Viewing & Modifying the resulting records.
Reviewing JDBC
© People Strategists www.peoplestrategists.com Slide 4 of 45
What are the pros
and cons of JDBC
Reviewing JDBC (Contd.)
© People Strategists www.peoplestrategists.com Slide 5 of 45
The following figure depicts the pros and cons of JDBC:
Pros Cons
Clean and simple SQL processing
Good performance with large data
Very good for small applications
Simple syntax so easy to learn
Complex if it is used in large projects
Large programming overhead
No encapsulation
Hard to implement MVC concept
Query is DBMS specific.
Reviewing JDBC (Contd.)
© People Strategists www.peoplestrategists.com Slide 6 of 45
Identifying the Need of Hibernate
While using traditional
methods to create Web
applications, you need to:
• Implement the business
logic in the application
for storing and
retrieving data from the
database.
To store data in a
relational database, you
need to:
• Convert the various
properties of a Java
class into primitive data
types of the relational
database.
• Map the class
properties with the
columns of a table in
the database.
To retrieve data from a
relational database, you
need to:
• Convert the database
values back into the
data types of the class
properties.
© People Strategists www.peoplestrategists.com Slide 7 of 45
You need to write additional code for handling conversion of values
between the data types of database and class properties.
This increases the application-development time and makes the
application error prone.
In addition, the following problems may occur in the application:
Scattered business logic and data manipulation code.
Difficulty in fixing compile-time or run-time errors.
Difficulty in managing the database connections.
Identifying the Need of Hibernate (Contd.)
© People Strategists www.peoplestrategists.com Slide 8 of 45
Most of the object-oriented applications use relational databases to
store and manage the application data.
The relational databases represent the data in tables whereas the data in
object-oriented applications is encapsulated in a class.
You can access a class by using its objects. However, to access the tabular
data, you need to use a query language.
As a result, it is not possible to directly store the objects in a relational
database.
These differences between object-oriented and relational database
paradigms are called impedance mismatch.
Introducing ORM
© People Strategists www.peoplestrategists.com Slide 9 of 45
Impedance mismatch exists at the following points:
Granularity:
 Refers to the mismatch in the number of classes that are mapped with a certain
number of database tables. For example, consider the following code snippet:
public class Employee
{
private String name;
private ConactNo contactno;
//Setters and getters
}
public class ConactNo {
private String MbNo.
private String LandlineNo.
//Setters and getters
}
 The EMPLOYEE table that stores employee information in the database contains
the columns as NAME and CONTACTNO.
 It is evident from the preceding code that a EMPLOYEE table is represented in
more than one class.
 Adding a new data type is easier in an object model than creating a new user-
defined column. Therefore, the object model is more granular than the relational
model.
Introducing ORM (Contd.)
© People Strategists www.peoplestrategists.com Slide 10 of 45
Subtypes (inheritance):
 Refers to the difference in the relationship among the classes in an application
and the tables in the database.
 Classes in the application are commonly related to each other through an
inheritance hierarchy. However, the tables in the database cannot be
represented through an inheritance hierarchy.
Identity:
 Refers to how the objects are differentiated in an application and in a relational
database.
 The relational database distinguishes an object instance on the basis of their
primary key. However, an object model distinguishes an object from the rest of
the objects on the basis of the object identity and object equality.
Association:
 Refers to the difference in the linking of classes in an application and the linking
of tables in the database.
 In an object model, two classes are linked by association. However, in relational
databases, the linking of tables is achieved with the help of foreign keys.
Introducing ORM (Contd.)
© People Strategists www.peoplestrategists.com Slide 11 of 45
Introducing ORM (Contd.)
To remove the impedance mismatch problem you need to use process
called Object-relational mapping (ORM).
In computing term ORM is a programming technique for converting data
between incompatible type systems in object-oriented programming
languages.
It helps in implementing data persistence by storing the values of class
properties in a database table. For example, consider the following code
snippet:
CREATE TABLE STUDENT
(
STUD_ID INT PRIMARY KEY NOT NULL,
STUD_NAME VARCHAR(20)
)
The Student class that is mapped with the STUDENT table can be created by
using the following code snippet:
class Student
{
int enrolment_no;
String name;
}
© People Strategists www.peoplestrategists.com Slide 12 of 45
Instances of the Student class
enrolment_no = 1002
name = “Joseph”
enrolment_no = 1003
name = “James”
STUDENT table
The following figure shows the mapping of the Student class with the
STUDENT table.
STUD_ID STUD_NAME
1002 Joseph
1003 James
Introducing ORM (Contd.)
© People Strategists www.peoplestrategists.com Slide 13 of 45
Introducing ORM (Contd.)
Java ORM Frameworks:
There are several persistent frameworks and ORM options in Java. A
persistent framework is an ORM service that stores and retrieves objects
into a relational database. Some of the ORM options are:
 Enterprise JavaBeans Entity Beans
 Java Data Objects
 Spring DAO
 Hibernate
 Castor
 TopLink
© People Strategists www.peoplestrategists.com Slide 14 of 45
Identifying Hibernate
What is
Hibernate?
© People Strategists www.peoplestrategists.com Slide 15 of 45
Hibernate is an ORM solution for JAVA introduced by Gavin King in 2001.
It is a powerful, high performance Object-Relational Persistence and
Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types
to SQL data types and relieve the developer from 95% of common data
persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to
handle all the work in persisting those objects based on the appropriate
O/R mechanisms and patterns.
Identifying Hibernate (Contd.)
© People Strategists www.peoplestrategists.com Slide 16 of 45
Some of the common advantage of hibernate are:
Open source and Lightweight: Hibernate framework is open source under
the Lesser General Public License (LGPL) license and lightweight.
Fast performance: The performance of hibernate framework is fast because
cache is internally used in hibernate framework.
Database Independent query: HQL (Hibernate Query Language) is the
object-oriented version of SQL. It generates the database independent
queries.
Automatic table creation: Hibernate framework provides the facility to
create the tables of the database automatically. So there is no need to
create tables in the database manually.
Simplifies complex join: To fetch data form multiple tables is easy in
hibernate framework.
Provides query statistics and database status: Hibernate supports Query
cache and provide statistics about query and database status.
Identifying the Advantages of Hibernate
© People Strategists www.peoplestrategists.com Slide 17 of 45
What are the
differences between
JDBC and
Hibernate?
Identifying Differences between JDBC and Hibernate
© People Strategists www.peoplestrategists.com Slide 18 of 45
JDBC Hibernate
Developers needs to write code
to map an object model's data
representation to a relational
data model and its corresponding
database schema.
JDBC supports only native
Structured Query Language (SQL).
Developer has to find out the
efficient way to access database.
Automatic mapping of Java
objects with database tables and
vice versa conversion is to be
taken care of by the developer
manually with lines of code.
Hibernate is flexible and powerful
ORM solution to map Java classes
to database tables. Hibernate
itself takes care of this mapping
using XML files.
Hibernate provides a powerful
query language Hibernate Query
Language that is expressed in a
familiar SQL like syntax.
Hibernate provides transparent
persistence and developer does
not need to write code explicitly
to map database tables tuples to
application objects during
interaction with RDBMS.
The following figure depicts the difference between JDBC and
hibernate.
Identifying Differences between JDBC and Hibernate (Contd.)
© People Strategists www.peoplestrategists.com Slide 19 of 45
What are the
difference between
EJB and Hibernate?
Identifying Differences between EJB and Hibernate
© People Strategists www.peoplestrategists.com Slide 20 of 45
Hibernate EJB
Hibernate is an open-source
technology.
Hibernate provides transparent
data persistence.
Implementation of Hibernate is
not dependent on a framework or
run-time environment.
Hibernate provides persistence
services with its own classes,
interfaces, and methods.
HQL is the query language
provided by Hibernate to manage
objects in a relational database.
EJB is a part of Java EE
specification.
In an EJB application, it is difficult
to switch from one database to
another.
Data persistence in EJB is
dependent on the run-time
environment called EJB container.
EJB provides data persistence
with Java Persistence API.
EJB provides Java Persistence
Query Language(JPQL) to query
the underlying database.
The following figure depicts the difference between EJB and
Hibernate.
Identifying Differences between EJB and Hibernate (Contd.)
© People Strategists www.peoplestrategists.com Slide 21 of 45
Hibernate is a collection of various constituent components that work
together to communicate with the database to ensure data integrity and
consistency.
The following figure depicts the architecture of hibernate:
Exploring Hibernate Architecture
Java Application
Hibernate
Criteria
SessionConfiguration
Query
Session Factory
Transaction
Persistent Object
JNDIJDBCJTA
© People Strategists www.peoplestrategists.com Slide 22 of 45
To persist data in the database, the applications communicate with the
Hibernate layer that contains the following core classes and interfaces of
the Hibernate API:
Configuration class:
 An instance of the Configuration class is used to represent the properties of
the configuration file of Hibernate.
 The instance of this class is created once during the initialization of the Hibernate
application.
 Hibernate uses this instance to read and parse the properties required to
connect to a database and application.
 An Instance of this class is used to create a SessionFactory instance. Once the
SessionFactory instance is created in the application, the Configuration
object is discarded.
 The Configuration object provides two keys components:
 Database Connection: This is handled through one or more configuration files
supported by Hibernate. These files are hibernate.properties and
hibernate.cfg.xml.
 Class Mapping Setup: This component creates the connection between the
Java classes and database tables..
Exploring Hibernate Architecture (Contd.)
© People Strategists www.peoplestrategists.com Slide 23 of 45
SessionFactory interface:
 An instance of the SessionFactory interface is created by using an object of
the Configuration class.
 This instance is used to create and open a session to communicate with a
database.
 A SessionFactory object is created and configured separately for each
database being connected.
Session interface:
 An instance of the Session interface is created with the help of the
SessionFactory object. It is used to communicate with a database.
Transaction interface:
 An object of the Transaction interface is created by using a Session object
and used to perform a logical unit of work from the database.
 The Hibernate framework uses the transaction implementation of various
available APIs, such as JDBC, JTA, and JNDI.
Exploring Hibernate Architecture (Contd.)
© People Strategists www.peoplestrategists.com Slide 24 of 45
Query interface: An object of the Query interface is used to create a query
that retrieves or stores data into the database.
Criteria interface: An object of the Criteria interface is used to create a
query that retrieves or stores data based on multiple conditions.
The following figure shows the working of the Hibernate classes and
interfaces.
Exploring Hibernate Architecture (Contd.)
© People Strategists www.peoplestrategists.com Slide 25 of 45
Ensure that you have latest version of java installed in your computer
system.
Select whether you want to install Hibernate on Windows, or Unix and
then proceed to the next step to download .zip file for windows and .tz
file for Unix.
Download the latest version of Hibernate from
http://www.hibernate.org/downloads.
At present, hibernate-release-4.3.10.Final version of the
hibernate is available.
Unzip the downloaded file it will give you directory structure as follows.
Downloading Hibernate
© People Strategists www.peoplestrategists.com Slide 26 of 45
Select whether you want to MySQL Java connector for Windows, or Unix
and then proceed to the next step to download .zip file for windows and
.tz file for Unix.
Download the latest version of MySQL Java connector from
https://dev.mysql.com/downloads/connector/j/
At present, mysql-connector-java-5.0.8 version of the MySQL Java
connector is available.
Unzip the downloaded file it will give you directory structure as follows.
Downloading MySQL Java Connector
© People Strategists www.peoplestrategists.com Slide 27 of 45
To connect with a database in Hibernate application, you need to set
various properties regarding driver class, user name, and password in the
hibernate.cfg.xml file
The structure of the hibernate.cfg.xml file is given in the following code
snippet:
Configuring Hibernate
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-
3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.username">SYSTEM</property>
.......
.......
.......
<mapping resource="Mapped_File.hbm.xml" />
</session-factory>
</hibernate-configuration>
© People Strategists www.peoplestrategists.com Slide 28 of 45
In the preceding code snippet, the hibernate.cfg.xml file contains the
following tags:
<?xml>: Defines the version and encoding type used for the XML
document.
<DOCTYPE>: Specifies the Document Type Definition (DTD) for the XML
elements. DTD specifies the grammar rule for the XML document. For
example, DTD for hibernate.cfg.xml file is specified as
http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd.
<hibernate-configuration>: Specifies all the configuration details
that the application uses to communicate with the underlying database.
<session-factory>: Contains the database and application specific
properties that a Session object uses to establish a communication link
between the application and the database.
<property>: Defines the various properties that are required to connect
with the database.
<mapping>: Specifies the name of the Hibernate mapping file that
defines the mapping of a database table to a class.
Configuring Hibernate (Contd.)
© People Strategists www.peoplestrategists.com Slide 29 of 45
The following properties are commonly set under the <property> tag:
JDBC properties: The JDBC properties are used to connect with a relational
database. The following JDBC properties are commonly used in a Hibernate
configuration file:
 hibernate.connection.driver_class: Specifies the database specific
driver name.
 hibernate.connection.url: Specifies the complete path along with the
port number and name of a database that needs to be connected with the
application.
 hibernate.connection.username: Specifies the user name that is used
to connect with a particular database.
 hibernate.connection.password: Specifies the password that is used
to connect with a particular database.
Configuring Hibernate (Contd.)
© People Strategists www.peoplestrategists.com Slide 30 of 45
Hibernate configuration properties: The Hibernate configuration properties
control the behavior of Hibernate at runtime. The following configurations
are commonly used in the Hibernate configuration file:
 hibernate.dialect: Specifies the database that is used to communicate
with the application. It accepts a class name corresponding to the database used
in the application. For example, to set the dialect property for the Oracle
database, you need to use the following code snippet:
<property name="dialect">
org.hibernate.dialect.OracleDialect </property>
 hibernate.show_sql: Specifies that the SQL statements are written on the
console during the execution of the application. It helps in identifying errors
during execution and improving the query performance. The following code
snippet is used to set the hibernate.show_sql property:
<property name = "hibernate.show_sql">
true</property>
Configuring Hibernate (Contd.)
© People Strategists www.peoplestrategists.com Slide 31 of 45
Hibernate miscellaneous properties: The Hibernate miscellaneous
properties specify the optional properties that are not mandatory to
connect with a database.
 The hibernate.current_session_context_class property specifies
the controller class that controls the scope of the current session in a Hibernate
application. This property takes the following values:
 thread: Specifies that the scope of the current session is managed by a thread
using which the session is started.
 jta: Specifies that the current session is bound to the currently running JTA
transaction.
 managed: Allows you to manually manage the session by creating, flushing,
and closing sessions.
 For example, consider the following code snippet:
<property name
hibernate.current_session_context_class>
thread </property>
Configuring Hibernate (Contd.)
© People Strategists www.peoplestrategists.com Slide 32 of 45
The following code illustrates how to configure Hibernate with MySQL
database:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property>
<property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property>
<!-- Assume test is the database name -->
<property name="hibernate.connection.url"> jdbc:mysql://localhost/test </property>
<property name="hibernate.connection.username"> root </property>
<property name="hibernate.connection.password"> root123 </property>
<!-- List of XML mapping files -->
<mapping resource="Employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Configuring Hibernate (Contd.)
© People Strategists www.peoplestrategists.com Slide 33 of 45
In a Hibernate application, a session acts as a pipeline between the
application and the database.
To store the application data in the database, you need to create a
Session object.
A session object in an application is created by using a SessionFactory
object.
To create a SessionFactory object, the application needs various
database specific configuration settings.
Hibernate specifies the configuration settings and information about the
mapping document in an XML file named hibernate.cfg.xml.
Hibernate provides the org.hibernate.cfg.Configuration class
that allows the application to specify the configuration properties and
mapping documents to create a SessionFactory object.
Creating a Hibernate Session
© People Strategists www.peoplestrategists.com Slide 34 of 45
The Configuration class provides the following methods to specify the
configuration properties and mapping documents to create a
SessionFactory object.
configure(): Loads the hibernate.cfg.xml file and initializes the object of
the Configuration class with the mappings and configuration
properties specified in this file.
getProperties(): Is used to fetch the properties for the configuration
that are configured using the configure()method.
applySettings(): Uses the ServiceRegistryBuilder object to
apply the settings fetched using the getProperties()method. It takes
the output of the getProperties() method as its parameter.
buildSessionFactory(): Uses the Configuration object
returned by the configure()method to instantiate a new
SessionFactory object. It takes ServiceRegistry object as its
parameter. This object carries the configuration settings that are to be
applied.
Creating a Hibernate Session (Contd.)
© People Strategists www.peoplestrategists.com Slide 35 of 45
The following code snippet illustrates how to create object of the
SessionFactory interface:
You can use the getSessionFactory() method to access the
Hibernate session in your application, as shown in the following code
snippet:
Creating a Hibernate Session (Contd.)
private static final SessionFactory sessionFactory;
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
sessionFactory=configuration.buildSessionFactory(serviceRegistry);
Session session =
HibernateUtil.getSessionFactory().getCurrentSession();
© People Strategists www.peoplestrategists.com Slide 36 of 45
The main function of the Session object is to offer create, read, and
delete operations for instances of mapped entity classes. Instances may
exist in one of the following three states at a given point in time:
transient: A new instance of a persistent class which is not associated with a
Session and has no representation in the database and no identifier value
is considered transient by Hibernate.
persistent: You can make a transient instance persistent by associating it
with a Session. A persistent instance has a representation in the database,
an identifier value and is associated with a Session.
detached: Once we close the Hibernate Session, the persistent instance
will become a detached instance.
Creating a Hibernate Session (Contd.)
© People Strategists www.peoplestrategists.com Slide 37 of 45
The following table contains some of the common methods available in
the Session object.
Creating a Hibernate Session (Contd.)
Method Description
Transaction
beginTransaction()
Begin a unit of work and return the associated Transaction object.
void cancelQuery() Cancel the execution of the current query.
void clear() Completely clear the session.
Connection close() End the session by releasing the JDBC connection and cleaning up.
Serializable
getIdentifier(Object
object)
Return the identifier value of the given entity as associated with this
session.
Query createFilter(Object
collection, String
queryString)
Create a new instance of Query for the given collection and filter
string.
Query createQuery(String
queryString)
Create a new instance of Query for the given HQL query string.
SQLQuery
createSQLQuery(String
queryString)
Create a new instance of SQLQuery for the given SQL query string.
void delete(Object
object)
Remove a persistent instance from the datastore.
© People Strategists www.peoplestrategists.com Slide 38 of 45
Creating a Hibernate Session (Contd.)
Method Description
void delete(String
entityName, Object
object)
Remove a persistent instance from the datastore.
Session get(String
entityName, Serializable
id)
Return the persistent instance of the given named entity with the
given identifier, or null if there is no such persistent instance.
SessionFactory
getSessionFactory()
Get the session factory which created this session.
Transaction
getTransaction()
Get the Transaction instance associated with this session.
boolean isConnected() Check if the session is currently connected.
boolean isOpen() Check if the session is still open.
Serializable save(Object
object)
Persist the given transient instance, first assigning a generated
identifier.
void saveOrUpdate(Object
object)
Either save(Object) or update(Object) the given instance.
void update(Object
object)
Update the persistent instance with the identifier of the given
detached instance.
void update(String
entityName, Object
object)
Update the persistent instance with the identifier of the given
detached instance.
© People Strategists www.peoplestrategists.com Slide 39 of 45
A Session instance is serializable if its persistent classes are serializable.
A typical transaction should use the following idiom:
Creating a Hibernate Session (Contd.)
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
// do some work
...
tx.commit();
}
catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}
© People Strategists www.peoplestrategists.com Slide 40 of 45
Consider a scenario where you need to store the employee details in a
relational database. However, the data types used to declare the
properties of the Employee class and the columns of the EMPLOYEE
table are different. Therefore, classes and its properties must be mapped
with the tables and its columns. The following figure depicts the
difference between the data types used in a class and a database table.
Configuring Mapping Properties
EMPLOYEE (table)
EmpID: int
EmpName: varchar
EmpAddress: varchar
EmpContactNumber: varchar
Employee (class)
empID: int
empName: String
empAddress: String
empContactNumber: String
© People Strategists www.peoplestrategists.com Slide 41 of 45
Hibernate allows you to map the classes and their properties with the
tables of the database in a configuration file.
The name of this mapping file has the following syntax:
<persistent_class_name>.hbm.xml.
The Hibernate mapping file overcomes the problem of difference
between the data types used in classes and columns of the tables.
The Hibernate mapping file contains mapping information of the class
data types with the database specific data types.
The Hibernate mapping file acts as a medium of communication
between the persistent classes and the database tables.
The Hibernate mapping file enables the communication by mapping the
data types used in the persistent classes with the database specific data
types by using the Hibernate types.
Configuring Mapping Properties (Contd.)
© People Strategists www.peoplestrategists.com Slide 42 of 45
Hibernate Types:
Provide an abstract representation of the underlying database types.
Allow you to develop the application without worrying about the target
database and the data types supported by it.
Provide you the flexibility to change the database without changing the
application code.
The following table lists some of the Hibernate built-in types along with the
corresponding Java and SQL data types.
Hibernate Type Java Type SQL Type
integer, long, short
Integer, int, long
short
NUMERIC, NUMBER, INT,
or other vendor
specific type.
character char CHAR
big_decimal java.math.BigDecimal NUMERIC, NUMBER
float, double float, double FLOAT, DOUBLE
boolean, yes_no,
true_false
java.lang.Boolean,
boolean
BOOLEAN, INT
string java.lang.String VARCHAR, VARCHAR2
date, time, timestamp java.util.Date
DATE, TIME, and
TIMESTAMP
Configuring Mapping Properties (Contd.)
© People Strategists www.peoplestrategists.com Slide 43 of 45
The following figure shows the communication of a persistent class with
a database table through the Hibernate mapping file.
Configuring Mapping Properties (Contd.)
EMPLOYEE (table)
EmpID: int
EmpName: varchar
EmpAddress: varchar
EmpContactNumber: varchar
Employee (class)
empID: int
empName: String
empAddress: String
empContactNumber: String
<hibernate-mapping>
<class name="EmployeeTest.Employee" table="EMPLOYEE"
schema="EMP">
<id name="empID" type="int">
<column name="EMPLOYEEID" />
</id>
<property name="EmpName" type="string">
<column name="EmpName" length="40" />
</property>
.............
.............
</class>
</hibernate-mapping>
Mapping file
© People Strategists www.peoplestrategists.com Slide 44 of 45
While mapping the persistent class objects with the tables in the
database, Hibernate classifies objects in the following types:
Entity type: Is an independent entity and has its own primary key in a
database table.
Value type: A value type object does not have an identifier. Therefore, a
value type object depends on an entity type object for its existence.
Configuring Mapping Properties (Contd.)
© People Strategists www.peoplestrategists.com Slide 45 of 45
Hibernate provides you with the following mapping techniques to create
and map the persistent classes of the application with the database
tables to retrieve and store data:
Using the Hibernate mapping file
Using annotations
Mapping Beans with the Database
© People Strategists www.peoplestrategists.com Slide 46 of 45
In this technique, you need to set values for the various mapping
elements in the Hibernate mapping file.
The Hibernate mapping file contains the following commonly used
elements:
<DOCTYPE>: Specifies the type of the current XML document and the name
of the Document Type Definition (DTD).
<hibernate-mapping>: Refers to the root mapping element that contains
other mapping elements, such as <class>, <id>, and <generator>.
<class>: Refers to the Java class that is mapped with a database table and
it contains the following commonly used attributes:
 name: Specifies the fully qualified class name of the persistent class.
 table: Specifies the name of the database table to which the Java class is
mapped.
 Mutable: Specifies whether the Java class is mutable. A class whose objects are
declared as read-only objects is referred to as the mutable class.
 schema: Specifies the schema of the database being mapped with the Java class.
Using the Hibernate Mapping File
© People Strategists www.peoplestrategists.com Slide 47 of 45
<id>: Refers to the primary key column of a database table. The commonly
used attributes of the <id> element are:
 name: Specifies the property name of the Java class that is mapped with the
primary key column of the database table.
 type: Specifies the Hibernate type that is used to map a property of the Java
class with the primary key column of a database table.
 column: Specifies the name of the primary key column of the database table.
<generator>: Refers to a Java class used to generate unique identifiers for
the instances of the persistent class in a database table. This element
defines the class name with the help of the class attribute. The commonly
used aliases as the value of the class attribute are:
 assigned:
 Increment
 Identity
 Sequence
 native
Using the Hibernate Mapping File (Contd.)
© People Strategists www.peoplestrategists.com Slide 48 of 45
<property>: Is used to map the properties of the Java class with the specific
columns of a database table. This element has the following commonly used
attributes:
 name: Specifies the name of a property of the Java class that is being mapped
with a column of the database table.
 type: Specifies the Hibernate type that is used to map a property of the Java
class with a column of the database table.
 column: Specifies the name of a column of the database table that is mapped
to a property of the Java class.
 length: Specifies the maximum number of characters that a column, which is
being mapped with a property of the Java class, can store.
<column>: Is used to specify a column that is to be mapped with a property of the
Java class. It is used within the <property> tag. However, this tag can be replaced
by using the column attribute of the <property> tag. The <column> tag has the
following commonly used attributes:
 name: Specifies the name of the column in the database table.
 length: Specifies the maximum number of characters that a column can store.
Using the Hibernate Mapping File (Contd.)
© People Strategists www.peoplestrategists.com Slide 49 of 45
The following code snippet map the Employee class with the EMPLOYEE
table in a database.
Using the Hibernate Mapping File (Contd.)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE" schema="EMP">
<id name="empid" type="int">
<column name="EMPID" />
<generator class="assigned" />
</id>
<property name="empname" type="string">
<column name="EMPNAME" length="20" />
</property>
<property name="empaddress" type="string">
<column name="EMPADDRESS" length="40" />
</property>
</class>
</hibernate-mapping>
© People Strategists www.peoplestrategists.com Slide 50 of 45
Consider a scenario where you need to create a simple hibernate JPA
project using eclipse to store employee records. Application should be
based on the following guideline:
Configuration of the hibernate should configured hibernate.cfg.xml
Activity: Creating a Simple Hibernate Java Application Using Eclipse
© People Strategists www.peoplestrategists.com Slide 51 of 45
In this technique, you map the elements of the table in the database
with the bean using annotations. The following annotations are
commonly used while mapping:
@Entity: Is used to specify a class as an entity bean. It is contained inside the
javax.persistence package.
@Table: Is used to specify the name of the table.
@Column: Is used to specify the column name. It contains the following attributes:
 name: Specifies the name of the column.
 length: Specifies the length of the column.
 nullable: Specifies the column to be NOT NULL.
 unique: Specifies the column to contain unique values.
@Id: Is used to define the column as an identifier or a primary key.
@GeneratedValue: This annotation is used to specify the identifier generation
strategy. The identifier generation strategies are of the following types:
 AUTO
 IDENTITY
 SEQUENCE
 TABLE
Using Annotations
© People Strategists www.peoplestrategists.com Slide 52 of 45
Consider a scenario where you are developing a Web page that accepts
the employee id of an employee from the user and displays the details
about that employee. The employee details need to be fetched from the
EMPLOYEE table stored in the database.
The Employee table displays the details in the database, as shown in the
following figure.
Using Annotations (Contd.)
EmpID EmpName EmpAddress EmpContact
238 JAMES JONES California 7728374859
239 JONAH DOMES Boston 7528384559
240 RICHARD PARKER New York 7238495867
© People Strategists www.peoplestrategists.com Slide 53 of 45
The following code snippet displays the EMPLOYEE table mapped with
the managed bean.
Using Annotations (Contd.)
import java.io.Serializable;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.persistence.*;
@Named("employee")
@RequestScoped
@Entity
@Table(name="Employee")
public class Employee implements Serializable
{
@Id @GeneratedValue
@Column(name="EmpID")
private int empID;
@Column(name="EmpName")
private String empName;
@Column(name="EmpAddress")
private String empAddress;
@Column(name="EmpContact")
private long empContact;
...............................
...............................
public Employee() {
}
}

Weitere ähnliche Inhalte

Was ist angesagt?

Hibernate ppt
Hibernate pptHibernate ppt
Hibernate pptAneega
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivityTanmoy Barman
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDBRavi Teja
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - JavaDrishti Bhalla
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginnersRahul Jain
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NETrchakra
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread SynchronizationBenj Del Mundo
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)GOPAL BASAK
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Aijaz Ali Abro
 

Was ist angesagt? (20)

Java Spring Framework
Java Spring FrameworkJava Spring Framework
Java Spring Framework
 
Hibernate ppt
Hibernate pptHibernate ppt
Hibernate ppt
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
JDBC: java DataBase connectivity
JDBC: java DataBase connectivityJDBC: java DataBase connectivity
JDBC: java DataBase connectivity
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Introduction to MongoDB
Introduction to MongoDBIntroduction to MongoDB
Introduction to MongoDB
 
Collections Api - Java
Collections Api - JavaCollections Api - Java
Collections Api - Java
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Introduction to ADO.NET
Introduction to ADO.NETIntroduction to ADO.NET
Introduction to ADO.NET
 
Java Thread Synchronization
Java Thread SynchronizationJava Thread Synchronization
Java Thread Synchronization
 
Getting started with entity framework
Getting started with entity framework Getting started with entity framework
Getting started with entity framework
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Document Object Model (DOM)
Document Object Model (DOM)Document Object Model (DOM)
Document Object Model (DOM)
 
Servlets
ServletsServlets
Servlets
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 

Ähnlich wie Hibernate I

Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetJayarajus
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggetsVirtual Nuggets
 
Nhibernate Part 1
Nhibernate   Part 1Nhibernate   Part 1
Nhibernate Part 1guest075fec
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast trackBinu Bhasuran
 
01 Persistence And Orm
01 Persistence And Orm01 Persistence And Orm
01 Persistence And OrmRanjan Kumar
 
BITM3730Week13.pptx
BITM3730Week13.pptxBITM3730Week13.pptx
BITM3730Week13.pptxMattMarino13
 
International Journal of Engineering and Science Invention (IJESI)
International Journal of Engineering and Science Invention (IJESI)International Journal of Engineering and Science Invention (IJESI)
International Journal of Engineering and Science Invention (IJESI)inventionjournals
 
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...Karen Thompson
 
2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.ppt2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.pptChadharris42
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaEdureka!
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5phanleson
 
Utilized Code Gen To Save Our Efforts In Sap Integration
Utilized Code Gen To Save Our Efforts In Sap IntegrationUtilized Code Gen To Save Our Efforts In Sap Integration
Utilized Code Gen To Save Our Efforts In Sap IntegrationGuo Albert
 
Improved Presentation and Facade Layer Operations for Software Engineering Pr...
Improved Presentation and Facade Layer Operations for Software Engineering Pr...Improved Presentation and Facade Layer Operations for Software Engineering Pr...
Improved Presentation and Facade Layer Operations for Software Engineering Pr...Dr. Amarjeet Singh
 
Object relationship mapping and hibernate
Object relationship mapping and hibernateObject relationship mapping and hibernate
Object relationship mapping and hibernateJoe Jacob
 
Managing Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsManaging Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsBuhake Sindi
 

Ähnlich wie Hibernate I (20)

Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ Nizampet
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
 
Nhibernate Part 1
Nhibernate   Part 1Nhibernate   Part 1
Nhibernate Part 1
 
Design patterns fast track
Design patterns fast trackDesign patterns fast track
Design patterns fast track
 
01 Persistence And Orm
01 Persistence And Orm01 Persistence And Orm
01 Persistence And Orm
 
BITM3730Week13.pptx
BITM3730Week13.pptxBITM3730Week13.pptx
BITM3730Week13.pptx
 
A02620109
A02620109A02620109
A02620109
 
International Journal of Engineering and Science Invention (IJESI)
International Journal of Engineering and Science Invention (IJESI)International Journal of Engineering and Science Invention (IJESI)
International Journal of Engineering and Science Invention (IJESI)
 
A02620109
A02620109A02620109
A02620109
 
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
Cis 555 Week 4 Assignment 2 Automated Teller Machine (Atm)...
 
2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.ppt2008_478_Lyons_ppt.ppt
2008_478_Lyons_ppt.ppt
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | Edureka
 
Data access
Data accessData access
Data access
 
Jdbc Lecture5
Jdbc Lecture5Jdbc Lecture5
Jdbc Lecture5
 
Utilized Code Gen To Save Our Efforts In Sap Integration
Utilized Code Gen To Save Our Efforts In Sap IntegrationUtilized Code Gen To Save Our Efforts In Sap Integration
Utilized Code Gen To Save Our Efforts In Sap Integration
 
Improved Presentation and Facade Layer Operations for Software Engineering Pr...
Improved Presentation and Facade Layer Operations for Software Engineering Pr...Improved Presentation and Facade Layer Operations for Software Engineering Pr...
Improved Presentation and Facade Layer Operations for Software Engineering Pr...
 
Object relationship mapping and hibernate
Object relationship mapping and hibernateObject relationship mapping and hibernate
Object relationship mapping and hibernate
 
Data Base
Data BaseData Base
Data Base
 
Managing Data in Jakarta EE Applications
Managing Data in Jakarta EE ApplicationsManaging Data in Jakarta EE Applications
Managing Data in Jakarta EE Applications
 
[iOS] Data Storage
[iOS] Data Storage[iOS] Data Storage
[iOS] Data Storage
 

Mehr von People Strategists (20)

MongoDB Session 3
MongoDB Session 3MongoDB Session 3
MongoDB Session 3
 
MongoDB Session 2
MongoDB Session 2MongoDB Session 2
MongoDB Session 2
 
MongoDB Session 1
MongoDB Session 1MongoDB Session 1
MongoDB Session 1
 
Android - Day 1
Android - Day 1Android - Day 1
Android - Day 1
 
Android - Day 2
Android - Day 2Android - Day 2
Android - Day 2
 
Overview of web services
Overview of web servicesOverview of web services
Overview of web services
 
Spring Framework - III
Spring Framework - IIISpring Framework - III
Spring Framework - III
 
Spring Framework-II
Spring Framework-IISpring Framework-II
Spring Framework-II
 
Spring Framework -I
Spring Framework -ISpring Framework -I
Spring Framework -I
 
Hibernate II
Hibernate IIHibernate II
Hibernate II
 
Hibernate III
Hibernate IIIHibernate III
Hibernate III
 
Identifing Listeners and Filters
Identifing Listeners and FiltersIdentifing Listeners and Filters
Identifing Listeners and Filters
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Agile Dev. II
Agile Dev. IIAgile Dev. II
Agile Dev. II
 
Agile Dev. I
Agile Dev. IAgile Dev. I
Agile Dev. I
 
Working with Servlets
Working with ServletsWorking with Servlets
Working with Servlets
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
 
JSP Technology II
JSP Technology IIJSP Technology II
JSP Technology II
 
JSP Technology I
JSP Technology IJSP Technology I
JSP Technology I
 
XML Schemas
XML SchemasXML Schemas
XML Schemas
 

Kürzlich hochgeladen

Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?XfilesPro
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 

Kürzlich hochgeladen (20)

Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?How to Remove Document Management Hurdles with X-Docs?
How to Remove Document Management Hurdles with X-Docs?
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 

Hibernate I

  • 1. © People Strategists www.peoplestrategists.com Slide 1 of 45 Hibernate Day 1
  • 2. © People Strategists www.peoplestrategists.com Slide 2 of 45 In this session, you will learn to: Explore the basics of hibernate Explore the hibernate framework Configure mapping properties Objectives
  • 3. © People Strategists www.peoplestrategists.com Slide 3 of 45 Java Database Connectivity (JDBC): Is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. Provides a complete set of interfaces that allows for portable access to an underlying database. Provides the same capabilities as ODBC, allowing Java programs to contain database-independent code. Library includes APIs for the following tasks that are commonly associated with database usage:  Making a connection to a database.  Creating SQL or MySQL statements.  Executing SQL or MySQL queries in the database.  Viewing & Modifying the resulting records. Reviewing JDBC
  • 4. © People Strategists www.peoplestrategists.com Slide 4 of 45 What are the pros and cons of JDBC Reviewing JDBC (Contd.)
  • 5. © People Strategists www.peoplestrategists.com Slide 5 of 45 The following figure depicts the pros and cons of JDBC: Pros Cons Clean and simple SQL processing Good performance with large data Very good for small applications Simple syntax so easy to learn Complex if it is used in large projects Large programming overhead No encapsulation Hard to implement MVC concept Query is DBMS specific. Reviewing JDBC (Contd.)
  • 6. © People Strategists www.peoplestrategists.com Slide 6 of 45 Identifying the Need of Hibernate While using traditional methods to create Web applications, you need to: • Implement the business logic in the application for storing and retrieving data from the database. To store data in a relational database, you need to: • Convert the various properties of a Java class into primitive data types of the relational database. • Map the class properties with the columns of a table in the database. To retrieve data from a relational database, you need to: • Convert the database values back into the data types of the class properties.
  • 7. © People Strategists www.peoplestrategists.com Slide 7 of 45 You need to write additional code for handling conversion of values between the data types of database and class properties. This increases the application-development time and makes the application error prone. In addition, the following problems may occur in the application: Scattered business logic and data manipulation code. Difficulty in fixing compile-time or run-time errors. Difficulty in managing the database connections. Identifying the Need of Hibernate (Contd.)
  • 8. © People Strategists www.peoplestrategists.com Slide 8 of 45 Most of the object-oriented applications use relational databases to store and manage the application data. The relational databases represent the data in tables whereas the data in object-oriented applications is encapsulated in a class. You can access a class by using its objects. However, to access the tabular data, you need to use a query language. As a result, it is not possible to directly store the objects in a relational database. These differences between object-oriented and relational database paradigms are called impedance mismatch. Introducing ORM
  • 9. © People Strategists www.peoplestrategists.com Slide 9 of 45 Impedance mismatch exists at the following points: Granularity:  Refers to the mismatch in the number of classes that are mapped with a certain number of database tables. For example, consider the following code snippet: public class Employee { private String name; private ConactNo contactno; //Setters and getters } public class ConactNo { private String MbNo. private String LandlineNo. //Setters and getters }  The EMPLOYEE table that stores employee information in the database contains the columns as NAME and CONTACTNO.  It is evident from the preceding code that a EMPLOYEE table is represented in more than one class.  Adding a new data type is easier in an object model than creating a new user- defined column. Therefore, the object model is more granular than the relational model. Introducing ORM (Contd.)
  • 10. © People Strategists www.peoplestrategists.com Slide 10 of 45 Subtypes (inheritance):  Refers to the difference in the relationship among the classes in an application and the tables in the database.  Classes in the application are commonly related to each other through an inheritance hierarchy. However, the tables in the database cannot be represented through an inheritance hierarchy. Identity:  Refers to how the objects are differentiated in an application and in a relational database.  The relational database distinguishes an object instance on the basis of their primary key. However, an object model distinguishes an object from the rest of the objects on the basis of the object identity and object equality. Association:  Refers to the difference in the linking of classes in an application and the linking of tables in the database.  In an object model, two classes are linked by association. However, in relational databases, the linking of tables is achieved with the help of foreign keys. Introducing ORM (Contd.)
  • 11. © People Strategists www.peoplestrategists.com Slide 11 of 45 Introducing ORM (Contd.) To remove the impedance mismatch problem you need to use process called Object-relational mapping (ORM). In computing term ORM is a programming technique for converting data between incompatible type systems in object-oriented programming languages. It helps in implementing data persistence by storing the values of class properties in a database table. For example, consider the following code snippet: CREATE TABLE STUDENT ( STUD_ID INT PRIMARY KEY NOT NULL, STUD_NAME VARCHAR(20) ) The Student class that is mapped with the STUDENT table can be created by using the following code snippet: class Student { int enrolment_no; String name; }
  • 12. © People Strategists www.peoplestrategists.com Slide 12 of 45 Instances of the Student class enrolment_no = 1002 name = “Joseph” enrolment_no = 1003 name = “James” STUDENT table The following figure shows the mapping of the Student class with the STUDENT table. STUD_ID STUD_NAME 1002 Joseph 1003 James Introducing ORM (Contd.)
  • 13. © People Strategists www.peoplestrategists.com Slide 13 of 45 Introducing ORM (Contd.) Java ORM Frameworks: There are several persistent frameworks and ORM options in Java. A persistent framework is an ORM service that stores and retrieves objects into a relational database. Some of the ORM options are:  Enterprise JavaBeans Entity Beans  Java Data Objects  Spring DAO  Hibernate  Castor  TopLink
  • 14. © People Strategists www.peoplestrategists.com Slide 14 of 45 Identifying Hibernate What is Hibernate?
  • 15. © People Strategists www.peoplestrategists.com Slide 15 of 45 Hibernate is an ORM solution for JAVA introduced by Gavin King in 2001. It is a powerful, high performance Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the developer from 95% of common data persistence related programming tasks. Hibernate sits between traditional Java objects and database server to handle all the work in persisting those objects based on the appropriate O/R mechanisms and patterns. Identifying Hibernate (Contd.)
  • 16. © People Strategists www.peoplestrategists.com Slide 16 of 45 Some of the common advantage of hibernate are: Open source and Lightweight: Hibernate framework is open source under the Lesser General Public License (LGPL) license and lightweight. Fast performance: The performance of hibernate framework is fast because cache is internally used in hibernate framework. Database Independent query: HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the database independent queries. Automatic table creation: Hibernate framework provides the facility to create the tables of the database automatically. So there is no need to create tables in the database manually. Simplifies complex join: To fetch data form multiple tables is easy in hibernate framework. Provides query statistics and database status: Hibernate supports Query cache and provide statistics about query and database status. Identifying the Advantages of Hibernate
  • 17. © People Strategists www.peoplestrategists.com Slide 17 of 45 What are the differences between JDBC and Hibernate? Identifying Differences between JDBC and Hibernate
  • 18. © People Strategists www.peoplestrategists.com Slide 18 of 45 JDBC Hibernate Developers needs to write code to map an object model's data representation to a relational data model and its corresponding database schema. JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database. Automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files. Hibernate provides a powerful query language Hibernate Query Language that is expressed in a familiar SQL like syntax. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. The following figure depicts the difference between JDBC and hibernate. Identifying Differences between JDBC and Hibernate (Contd.)
  • 19. © People Strategists www.peoplestrategists.com Slide 19 of 45 What are the difference between EJB and Hibernate? Identifying Differences between EJB and Hibernate
  • 20. © People Strategists www.peoplestrategists.com Slide 20 of 45 Hibernate EJB Hibernate is an open-source technology. Hibernate provides transparent data persistence. Implementation of Hibernate is not dependent on a framework or run-time environment. Hibernate provides persistence services with its own classes, interfaces, and methods. HQL is the query language provided by Hibernate to manage objects in a relational database. EJB is a part of Java EE specification. In an EJB application, it is difficult to switch from one database to another. Data persistence in EJB is dependent on the run-time environment called EJB container. EJB provides data persistence with Java Persistence API. EJB provides Java Persistence Query Language(JPQL) to query the underlying database. The following figure depicts the difference between EJB and Hibernate. Identifying Differences between EJB and Hibernate (Contd.)
  • 21. © People Strategists www.peoplestrategists.com Slide 21 of 45 Hibernate is a collection of various constituent components that work together to communicate with the database to ensure data integrity and consistency. The following figure depicts the architecture of hibernate: Exploring Hibernate Architecture Java Application Hibernate Criteria SessionConfiguration Query Session Factory Transaction Persistent Object JNDIJDBCJTA
  • 22. © People Strategists www.peoplestrategists.com Slide 22 of 45 To persist data in the database, the applications communicate with the Hibernate layer that contains the following core classes and interfaces of the Hibernate API: Configuration class:  An instance of the Configuration class is used to represent the properties of the configuration file of Hibernate.  The instance of this class is created once during the initialization of the Hibernate application.  Hibernate uses this instance to read and parse the properties required to connect to a database and application.  An Instance of this class is used to create a SessionFactory instance. Once the SessionFactory instance is created in the application, the Configuration object is discarded.  The Configuration object provides two keys components:  Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.  Class Mapping Setup: This component creates the connection between the Java classes and database tables.. Exploring Hibernate Architecture (Contd.)
  • 23. © People Strategists www.peoplestrategists.com Slide 23 of 45 SessionFactory interface:  An instance of the SessionFactory interface is created by using an object of the Configuration class.  This instance is used to create and open a session to communicate with a database.  A SessionFactory object is created and configured separately for each database being connected. Session interface:  An instance of the Session interface is created with the help of the SessionFactory object. It is used to communicate with a database. Transaction interface:  An object of the Transaction interface is created by using a Session object and used to perform a logical unit of work from the database.  The Hibernate framework uses the transaction implementation of various available APIs, such as JDBC, JTA, and JNDI. Exploring Hibernate Architecture (Contd.)
  • 24. © People Strategists www.peoplestrategists.com Slide 24 of 45 Query interface: An object of the Query interface is used to create a query that retrieves or stores data into the database. Criteria interface: An object of the Criteria interface is used to create a query that retrieves or stores data based on multiple conditions. The following figure shows the working of the Hibernate classes and interfaces. Exploring Hibernate Architecture (Contd.)
  • 25. © People Strategists www.peoplestrategists.com Slide 25 of 45 Ensure that you have latest version of java installed in your computer system. Select whether you want to install Hibernate on Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix. Download the latest version of Hibernate from http://www.hibernate.org/downloads. At present, hibernate-release-4.3.10.Final version of the hibernate is available. Unzip the downloaded file it will give you directory structure as follows. Downloading Hibernate
  • 26. © People Strategists www.peoplestrategists.com Slide 26 of 45 Select whether you want to MySQL Java connector for Windows, or Unix and then proceed to the next step to download .zip file for windows and .tz file for Unix. Download the latest version of MySQL Java connector from https://dev.mysql.com/downloads/connector/j/ At present, mysql-connector-java-5.0.8 version of the MySQL Java connector is available. Unzip the downloaded file it will give you directory structure as follows. Downloading MySQL Java Connector
  • 27. © People Strategists www.peoplestrategists.com Slide 27 of 45 To connect with a database in Hibernate application, you need to set various properties regarding driver class, user name, and password in the hibernate.cfg.xml file The structure of the hibernate.cfg.xml file is given in the following code snippet: Configuring Hibernate <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration- 3.0.dtd"> <hibernate-configuration> <session-factory> <property name="connection.username">SYSTEM</property> ....... ....... ....... <mapping resource="Mapped_File.hbm.xml" /> </session-factory> </hibernate-configuration>
  • 28. © People Strategists www.peoplestrategists.com Slide 28 of 45 In the preceding code snippet, the hibernate.cfg.xml file contains the following tags: <?xml>: Defines the version and encoding type used for the XML document. <DOCTYPE>: Specifies the Document Type Definition (DTD) for the XML elements. DTD specifies the grammar rule for the XML document. For example, DTD for hibernate.cfg.xml file is specified as http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd. <hibernate-configuration>: Specifies all the configuration details that the application uses to communicate with the underlying database. <session-factory>: Contains the database and application specific properties that a Session object uses to establish a communication link between the application and the database. <property>: Defines the various properties that are required to connect with the database. <mapping>: Specifies the name of the Hibernate mapping file that defines the mapping of a database table to a class. Configuring Hibernate (Contd.)
  • 29. © People Strategists www.peoplestrategists.com Slide 29 of 45 The following properties are commonly set under the <property> tag: JDBC properties: The JDBC properties are used to connect with a relational database. The following JDBC properties are commonly used in a Hibernate configuration file:  hibernate.connection.driver_class: Specifies the database specific driver name.  hibernate.connection.url: Specifies the complete path along with the port number and name of a database that needs to be connected with the application.  hibernate.connection.username: Specifies the user name that is used to connect with a particular database.  hibernate.connection.password: Specifies the password that is used to connect with a particular database. Configuring Hibernate (Contd.)
  • 30. © People Strategists www.peoplestrategists.com Slide 30 of 45 Hibernate configuration properties: The Hibernate configuration properties control the behavior of Hibernate at runtime. The following configurations are commonly used in the Hibernate configuration file:  hibernate.dialect: Specifies the database that is used to communicate with the application. It accepts a class name corresponding to the database used in the application. For example, to set the dialect property for the Oracle database, you need to use the following code snippet: <property name="dialect"> org.hibernate.dialect.OracleDialect </property>  hibernate.show_sql: Specifies that the SQL statements are written on the console during the execution of the application. It helps in identifying errors during execution and improving the query performance. The following code snippet is used to set the hibernate.show_sql property: <property name = "hibernate.show_sql"> true</property> Configuring Hibernate (Contd.)
  • 31. © People Strategists www.peoplestrategists.com Slide 31 of 45 Hibernate miscellaneous properties: The Hibernate miscellaneous properties specify the optional properties that are not mandatory to connect with a database.  The hibernate.current_session_context_class property specifies the controller class that controls the scope of the current session in a Hibernate application. This property takes the following values:  thread: Specifies that the scope of the current session is managed by a thread using which the session is started.  jta: Specifies that the current session is bound to the currently running JTA transaction.  managed: Allows you to manually manage the session by creating, flushing, and closing sessions.  For example, consider the following code snippet: <property name hibernate.current_session_context_class> thread </property> Configuring Hibernate (Contd.)
  • 32. © People Strategists www.peoplestrategists.com Slide 32 of 45 The following code illustrates how to configure Hibernate with MySQL database: <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <property name="hibernate.dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver </property> <!-- Assume test is the database name --> <property name="hibernate.connection.url"> jdbc:mysql://localhost/test </property> <property name="hibernate.connection.username"> root </property> <property name="hibernate.connection.password"> root123 </property> <!-- List of XML mapping files --> <mapping resource="Employee.hbm.xml"/> </session-factory> </hibernate-configuration> Configuring Hibernate (Contd.)
  • 33. © People Strategists www.peoplestrategists.com Slide 33 of 45 In a Hibernate application, a session acts as a pipeline between the application and the database. To store the application data in the database, you need to create a Session object. A session object in an application is created by using a SessionFactory object. To create a SessionFactory object, the application needs various database specific configuration settings. Hibernate specifies the configuration settings and information about the mapping document in an XML file named hibernate.cfg.xml. Hibernate provides the org.hibernate.cfg.Configuration class that allows the application to specify the configuration properties and mapping documents to create a SessionFactory object. Creating a Hibernate Session
  • 34. © People Strategists www.peoplestrategists.com Slide 34 of 45 The Configuration class provides the following methods to specify the configuration properties and mapping documents to create a SessionFactory object. configure(): Loads the hibernate.cfg.xml file and initializes the object of the Configuration class with the mappings and configuration properties specified in this file. getProperties(): Is used to fetch the properties for the configuration that are configured using the configure()method. applySettings(): Uses the ServiceRegistryBuilder object to apply the settings fetched using the getProperties()method. It takes the output of the getProperties() method as its parameter. buildSessionFactory(): Uses the Configuration object returned by the configure()method to instantiate a new SessionFactory object. It takes ServiceRegistry object as its parameter. This object carries the configuration settings that are to be applied. Creating a Hibernate Session (Contd.)
  • 35. © People Strategists www.peoplestrategists.com Slide 35 of 45 The following code snippet illustrates how to create object of the SessionFactory interface: You can use the getSessionFactory() method to access the Hibernate session in your application, as shown in the following code snippet: Creating a Hibernate Session (Contd.) private static final SessionFactory sessionFactory; Configuration configuration = new Configuration().configure(); ServiceRegistryBuilder registry = new ServiceRegistryBuilder(); registry.applySettings(configuration.getProperties()); ServiceRegistry serviceRegistry = registry.buildServiceRegistry(); sessionFactory=configuration.buildSessionFactory(serviceRegistry); Session session = HibernateUtil.getSessionFactory().getCurrentSession();
  • 36. © People Strategists www.peoplestrategists.com Slide 36 of 45 The main function of the Session object is to offer create, read, and delete operations for instances of mapped entity classes. Instances may exist in one of the following three states at a given point in time: transient: A new instance of a persistent class which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate. persistent: You can make a transient instance persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session. detached: Once we close the Hibernate Session, the persistent instance will become a detached instance. Creating a Hibernate Session (Contd.)
  • 37. © People Strategists www.peoplestrategists.com Slide 37 of 45 The following table contains some of the common methods available in the Session object. Creating a Hibernate Session (Contd.) Method Description Transaction beginTransaction() Begin a unit of work and return the associated Transaction object. void cancelQuery() Cancel the execution of the current query. void clear() Completely clear the session. Connection close() End the session by releasing the JDBC connection and cleaning up. Serializable getIdentifier(Object object) Return the identifier value of the given entity as associated with this session. Query createFilter(Object collection, String queryString) Create a new instance of Query for the given collection and filter string. Query createQuery(String queryString) Create a new instance of Query for the given HQL query string. SQLQuery createSQLQuery(String queryString) Create a new instance of SQLQuery for the given SQL query string. void delete(Object object) Remove a persistent instance from the datastore.
  • 38. © People Strategists www.peoplestrategists.com Slide 38 of 45 Creating a Hibernate Session (Contd.) Method Description void delete(String entityName, Object object) Remove a persistent instance from the datastore. Session get(String entityName, Serializable id) Return the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance. SessionFactory getSessionFactory() Get the session factory which created this session. Transaction getTransaction() Get the Transaction instance associated with this session. boolean isConnected() Check if the session is currently connected. boolean isOpen() Check if the session is still open. Serializable save(Object object) Persist the given transient instance, first assigning a generated identifier. void saveOrUpdate(Object object) Either save(Object) or update(Object) the given instance. void update(Object object) Update the persistent instance with the identifier of the given detached instance. void update(String entityName, Object object) Update the persistent instance with the identifier of the given detached instance.
  • 39. © People Strategists www.peoplestrategists.com Slide 39 of 45 A Session instance is serializable if its persistent classes are serializable. A typical transaction should use the following idiom: Creating a Hibernate Session (Contd.) Session session = factory.openSession(); Transaction tx = null; try { tx = session.beginTransaction(); // do some work ... tx.commit(); } catch (Exception e) { if (tx!=null) tx.rollback(); e.printStackTrace(); }finally { session.close(); }
  • 40. © People Strategists www.peoplestrategists.com Slide 40 of 45 Consider a scenario where you need to store the employee details in a relational database. However, the data types used to declare the properties of the Employee class and the columns of the EMPLOYEE table are different. Therefore, classes and its properties must be mapped with the tables and its columns. The following figure depicts the difference between the data types used in a class and a database table. Configuring Mapping Properties EMPLOYEE (table) EmpID: int EmpName: varchar EmpAddress: varchar EmpContactNumber: varchar Employee (class) empID: int empName: String empAddress: String empContactNumber: String
  • 41. © People Strategists www.peoplestrategists.com Slide 41 of 45 Hibernate allows you to map the classes and their properties with the tables of the database in a configuration file. The name of this mapping file has the following syntax: <persistent_class_name>.hbm.xml. The Hibernate mapping file overcomes the problem of difference between the data types used in classes and columns of the tables. The Hibernate mapping file contains mapping information of the class data types with the database specific data types. The Hibernate mapping file acts as a medium of communication between the persistent classes and the database tables. The Hibernate mapping file enables the communication by mapping the data types used in the persistent classes with the database specific data types by using the Hibernate types. Configuring Mapping Properties (Contd.)
  • 42. © People Strategists www.peoplestrategists.com Slide 42 of 45 Hibernate Types: Provide an abstract representation of the underlying database types. Allow you to develop the application without worrying about the target database and the data types supported by it. Provide you the flexibility to change the database without changing the application code. The following table lists some of the Hibernate built-in types along with the corresponding Java and SQL data types. Hibernate Type Java Type SQL Type integer, long, short Integer, int, long short NUMERIC, NUMBER, INT, or other vendor specific type. character char CHAR big_decimal java.math.BigDecimal NUMERIC, NUMBER float, double float, double FLOAT, DOUBLE boolean, yes_no, true_false java.lang.Boolean, boolean BOOLEAN, INT string java.lang.String VARCHAR, VARCHAR2 date, time, timestamp java.util.Date DATE, TIME, and TIMESTAMP Configuring Mapping Properties (Contd.)
  • 43. © People Strategists www.peoplestrategists.com Slide 43 of 45 The following figure shows the communication of a persistent class with a database table through the Hibernate mapping file. Configuring Mapping Properties (Contd.) EMPLOYEE (table) EmpID: int EmpName: varchar EmpAddress: varchar EmpContactNumber: varchar Employee (class) empID: int empName: String empAddress: String empContactNumber: String <hibernate-mapping> <class name="EmployeeTest.Employee" table="EMPLOYEE" schema="EMP"> <id name="empID" type="int"> <column name="EMPLOYEEID" /> </id> <property name="EmpName" type="string"> <column name="EmpName" length="40" /> </property> ............. ............. </class> </hibernate-mapping> Mapping file
  • 44. © People Strategists www.peoplestrategists.com Slide 44 of 45 While mapping the persistent class objects with the tables in the database, Hibernate classifies objects in the following types: Entity type: Is an independent entity and has its own primary key in a database table. Value type: A value type object does not have an identifier. Therefore, a value type object depends on an entity type object for its existence. Configuring Mapping Properties (Contd.)
  • 45. © People Strategists www.peoplestrategists.com Slide 45 of 45 Hibernate provides you with the following mapping techniques to create and map the persistent classes of the application with the database tables to retrieve and store data: Using the Hibernate mapping file Using annotations Mapping Beans with the Database
  • 46. © People Strategists www.peoplestrategists.com Slide 46 of 45 In this technique, you need to set values for the various mapping elements in the Hibernate mapping file. The Hibernate mapping file contains the following commonly used elements: <DOCTYPE>: Specifies the type of the current XML document and the name of the Document Type Definition (DTD). <hibernate-mapping>: Refers to the root mapping element that contains other mapping elements, such as <class>, <id>, and <generator>. <class>: Refers to the Java class that is mapped with a database table and it contains the following commonly used attributes:  name: Specifies the fully qualified class name of the persistent class.  table: Specifies the name of the database table to which the Java class is mapped.  Mutable: Specifies whether the Java class is mutable. A class whose objects are declared as read-only objects is referred to as the mutable class.  schema: Specifies the schema of the database being mapped with the Java class. Using the Hibernate Mapping File
  • 47. © People Strategists www.peoplestrategists.com Slide 47 of 45 <id>: Refers to the primary key column of a database table. The commonly used attributes of the <id> element are:  name: Specifies the property name of the Java class that is mapped with the primary key column of the database table.  type: Specifies the Hibernate type that is used to map a property of the Java class with the primary key column of a database table.  column: Specifies the name of the primary key column of the database table. <generator>: Refers to a Java class used to generate unique identifiers for the instances of the persistent class in a database table. This element defines the class name with the help of the class attribute. The commonly used aliases as the value of the class attribute are:  assigned:  Increment  Identity  Sequence  native Using the Hibernate Mapping File (Contd.)
  • 48. © People Strategists www.peoplestrategists.com Slide 48 of 45 <property>: Is used to map the properties of the Java class with the specific columns of a database table. This element has the following commonly used attributes:  name: Specifies the name of a property of the Java class that is being mapped with a column of the database table.  type: Specifies the Hibernate type that is used to map a property of the Java class with a column of the database table.  column: Specifies the name of a column of the database table that is mapped to a property of the Java class.  length: Specifies the maximum number of characters that a column, which is being mapped with a property of the Java class, can store. <column>: Is used to specify a column that is to be mapped with a property of the Java class. It is used within the <property> tag. However, this tag can be replaced by using the column attribute of the <property> tag. The <column> tag has the following commonly used attributes:  name: Specifies the name of the column in the database table.  length: Specifies the maximum number of characters that a column can store. Using the Hibernate Mapping File (Contd.)
  • 49. © People Strategists www.peoplestrategists.com Slide 49 of 45 The following code snippet map the Employee class with the EMPLOYEE table in a database. Using the Hibernate Mapping File (Contd.) <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="Employee" table="EMPLOYEE" schema="EMP"> <id name="empid" type="int"> <column name="EMPID" /> <generator class="assigned" /> </id> <property name="empname" type="string"> <column name="EMPNAME" length="20" /> </property> <property name="empaddress" type="string"> <column name="EMPADDRESS" length="40" /> </property> </class> </hibernate-mapping>
  • 50. © People Strategists www.peoplestrategists.com Slide 50 of 45 Consider a scenario where you need to create a simple hibernate JPA project using eclipse to store employee records. Application should be based on the following guideline: Configuration of the hibernate should configured hibernate.cfg.xml Activity: Creating a Simple Hibernate Java Application Using Eclipse
  • 51. © People Strategists www.peoplestrategists.com Slide 51 of 45 In this technique, you map the elements of the table in the database with the bean using annotations. The following annotations are commonly used while mapping: @Entity: Is used to specify a class as an entity bean. It is contained inside the javax.persistence package. @Table: Is used to specify the name of the table. @Column: Is used to specify the column name. It contains the following attributes:  name: Specifies the name of the column.  length: Specifies the length of the column.  nullable: Specifies the column to be NOT NULL.  unique: Specifies the column to contain unique values. @Id: Is used to define the column as an identifier or a primary key. @GeneratedValue: This annotation is used to specify the identifier generation strategy. The identifier generation strategies are of the following types:  AUTO  IDENTITY  SEQUENCE  TABLE Using Annotations
  • 52. © People Strategists www.peoplestrategists.com Slide 52 of 45 Consider a scenario where you are developing a Web page that accepts the employee id of an employee from the user and displays the details about that employee. The employee details need to be fetched from the EMPLOYEE table stored in the database. The Employee table displays the details in the database, as shown in the following figure. Using Annotations (Contd.) EmpID EmpName EmpAddress EmpContact 238 JAMES JONES California 7728374859 239 JONAH DOMES Boston 7528384559 240 RICHARD PARKER New York 7238495867
  • 53. © People Strategists www.peoplestrategists.com Slide 53 of 45 The following code snippet displays the EMPLOYEE table mapped with the managed bean. Using Annotations (Contd.) import java.io.Serializable; import javax.inject.Named; import javax.enterprise.context.RequestScoped; import javax.persistence.*; @Named("employee") @RequestScoped @Entity @Table(name="Employee") public class Employee implements Serializable { @Id @GeneratedValue @Column(name="EmpID") private int empID; @Column(name="EmpName") private String empName; @Column(name="EmpAddress") private String empAddress; @Column(name="EmpContact") private long empContact; ............................... ............................... public Employee() { } }