KEMBAR78
Hibernate Training Session1 | PPTX
Prepared By Asad Khan
What is Hibernate means?
Animals that sleep through the winter, like bears, squirrels, bat etc.
Hibernation is characterized by low body temperature, slow breathing and heart rate,
and low metabolic rate.
Can Human be Hibernate in
Future?
The extreme survival tricks of hibernating animals… and the occasional human…
could help us overcome life-threatening injuries, as Frank Swain discovers.
In Java world Hibernate is a well-
known ORM Framework
What is an ORM?
Object Relational Mapping (ORM) is a programming technique to access the data
from source which is incompatible with object orientated paradigm.
Why do we need ORM?
 Speeding development/Huge reduction in code.
 DBMS Compatibility
 Focus on Business more
 Make CRUD operation to behave OOP way
 Cache mechanism
Typical flow of an ORM
ORM act as a bridge b/w Object oriented application and relational database.
Other ORMs?
Is there any other ORMs?
 Eclipse Link
 Apache Cayenne
 Top Link
 Open JPA
Then Why Hibernate?
 Popularity
 Performance
 Vast support/Help
 Reliable
 JPA 2.1 compliant
 Cache support
Comparison with JDBC
Lets see their fight in eclipse IDE
HIBERNATE JDBC
Lets Begin Hibernate
JPA
Hibernate Architecture
Hibernate Core Classes Flow
Read
Configuration
and setup
hibernate
Manage Session
/Create Session
Make group of
dependent
instruction to
single
Execute single
instruction
Execute
HQL
Act as a
Where
clause
Closer look of Hibernate and JPA
Hibernate does more than JPA
What is JPA
History
 There were no standard for ORM until JPA introduced.
 JPA 1.0 was born in 2006 (Java EE 5)/ Influenced by Hibernate.
So What is it?
 JPA is a specification to standardize ORM-APIs or
specification for accessing, persisting and managing the data
between Java objects and the relational database.
 It means it went through the Java Community Process.
 Its specification # is JSR338
(https://jcp.org/en/jsr/detail?id=338)
 Following are implementation of JPA:
1)Eclipse Link 2) Hibernate 3)Open JPA
 These are interchangeable or no vendor locking.
Hibernate Setup
We will be using Hibernate version 4.3.7 in this training
and you can get from below link:
http://hibernate.org/orm/downloads
Hibernate JBOSS Tool for Eclipse:
http://download.jboss.org/jbosstools/updates/stable/lu
na/
Basic Setup for Hibernate
1. Create Java SE/EE Project.
2. Create Hibernate configuration file. Note: more
about this configuration file in next slide
3. Create Java Bean/ Class (Persistent Class).Note: more
about this class in next slide
4. Create Mapping File of that Class.
5. Map this class in Hibernate Configuration file.
Hibernate Configuration Properties
hibernate.use_sql_comments: true /false (true means show, false means don’t)
hibernate.format_sql: Pretty print the SQL in the log and console. e.g. true | false
hibernate.dialect: The classname of a Hibernate org.hibernate.dialect.Dialect
which allows Hibernate to generate SQL optimized for a particular relational
database.e.g. full.classname.of.Dialect
hibernate.show_sql: Write all SQL statements to console. This is an alternative to
setting the log category org.hibernate.SQL to debug.
e.g. true | false
hibernate.default_schema: Qualify unqualified table names with the given
schema/tablespace in generated SQL. e.g. SCHEMA_NAME
hibernate.hbm2ddl.auto: Automatically validates or exports schema DDL to the
database when the SessionFactory is created. With create-drop, the database
schema will be dropped when the SessionFactory is closed explicitly.
e.g. validate | update | create | create-drop
Following rules must be followed
when declaring Persistent Class
The four main rules of persistent classes :
 Implement a no-argument constructor
 Provide an identifier property (optional)
 Prefer non-final classes (optional)
 Declare accessors and mutators for persistent
fields (optional)
See the Employee class example in code.
Mapping Data Types
Types of Generator in Hibernate
 Assigned: lets the application assign an identifier to the object before save() is
called. This is the default strategy if no <generator> element is specified.
 Identity: supports identity columns in DB2, MySQL, MS SQL Server, Sybase
and Hypersonic SQL. The returned identifier is of type long, short or int.
 Sequence: uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a
generator in Interbase. The returned identifier is of type long, short or int.
 Uuid: uses a 128-bit UUID algorithm to generate identifiers of type string that
are unique within a network (the IP address is used). The UUID is encoded as a
string of 32 hexadecimal digits in length.
 Increment: generates identifiers of type long, short or int that are unique only
when no other process is inserting data into the same table.
There are many more classes for generator. Please visit the following site:
https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html
What is an Entity
 Entity : An entity is something that exists in itself,
actually or potentially, concretely or abstractly,
physically or not physically (conceptually).
Attribute
A property, or a conclusion of a characteristic of an entity
or substance or An attribute is a characteristic of
an entity.
Entity type or Value(Attribute) type
Any piece of data can be expressed as entity type or value
type:
 Entity Types:
Entities have a unique identity means exist independently and define
their own lifecycle., which stays the same despite of changes in the
properties of the object. For example Human, mobile, computer etc.
 Value Types
A value type do not define their own lifecycle. We say that they are
"owned" by something else (specifically an entity) which defines
their lifecycle. For Example: name, address, age of Employee, hand
of human, nip of a pen, wheel of a car, companies history of an
employee etc.
Value types are further classified into 3 sub-categories: basic types,
composite types and collection types.
• Basic Types: age, name, sex of an employee in single value.
• Composite types: aggregate values of basic types for i.e. address of
employee contain (country , state ,city and street).
• Collection types: collection of data for i.e. companies history of an
employee, daily activities of an employee.
Composite Value Type and its mapping with
an Entity
“Address” as a composite value type of an employee.
Lets see the example of mapping with an entity in code.
Collection Value Type and its mapping with
an Entity
In hibernate always declare a collection variable type by their
parent interface. For example Set, List, Map, Collection etc.
Because when we get back the collection object from
hibernate its type will be change by hibernate. It won’t be the
Java HashSet or ArrayList or HashMap, Its type will be in
specialized form.
Uni-directional and Bi-directional relationship
Uni-directional
Bi-directional
Recommended approach make relationship bidirectional in class.
Collection Value Type as HashSet Example
HashSet Properties:
 A Set represents a mathematical set.
 It is a Collection that, unlike List, does not allow
duplicates.
 There must not be two elements of a Set, say e1 and e2,
such that e1.equals(e2).
 The add method of Set returns false if you try to add a
duplicate element.
 HashSet allows at most one null element.
 HashSet is faster than other implementations of Set,
TreeSet and LinkedHashSet.
Lets see in action the “Employee Activities” as a collection
value type of an employee using HashSet in a program.
Collection Value Type as ArrayList Example
 An ArrayList is an ordered collection
 Permits null elements
 It is not synchronized
Lets see in action the “Past Companies” as a collection
value type of an employee using ArrayList in a program.
Collection Value Type as HashMap Example
 No guarantees as to the order of the map.
 Uniqueness guarantee.
 No guarantee that the order will remain constant.
 It is unsynchronized and permits nulls.
Lets see HashMap collection value type in an action
using “Employee Roles” in a program.
What's Next
Next we will do Entity relationship.
 One-to-one
 One-to-many
 Many-to-one
See You Next Time

Hibernate Training Session1

  • 1.
  • 2.
    What is Hibernatemeans? Animals that sleep through the winter, like bears, squirrels, bat etc. Hibernation is characterized by low body temperature, slow breathing and heart rate, and low metabolic rate.
  • 3.
    Can Human beHibernate in Future? The extreme survival tricks of hibernating animals… and the occasional human… could help us overcome life-threatening injuries, as Frank Swain discovers.
  • 4.
    In Java worldHibernate is a well- known ORM Framework What is an ORM? Object Relational Mapping (ORM) is a programming technique to access the data from source which is incompatible with object orientated paradigm. Why do we need ORM?  Speeding development/Huge reduction in code.  DBMS Compatibility  Focus on Business more  Make CRUD operation to behave OOP way  Cache mechanism
  • 5.
    Typical flow ofan ORM ORM act as a bridge b/w Object oriented application and relational database.
  • 6.
    Other ORMs? Is thereany other ORMs?  Eclipse Link  Apache Cayenne  Top Link  Open JPA Then Why Hibernate?  Popularity  Performance  Vast support/Help  Reliable  JPA 2.1 compliant  Cache support
  • 7.
    Comparison with JDBC Letssee their fight in eclipse IDE HIBERNATE JDBC
  • 8.
  • 9.
  • 11.
    Hibernate Core ClassesFlow Read Configuration and setup hibernate Manage Session /Create Session Make group of dependent instruction to single Execute single instruction Execute HQL Act as a Where clause
  • 12.
    Closer look ofHibernate and JPA Hibernate does more than JPA
  • 13.
    What is JPA History There were no standard for ORM until JPA introduced.  JPA 1.0 was born in 2006 (Java EE 5)/ Influenced by Hibernate. So What is it?  JPA is a specification to standardize ORM-APIs or specification for accessing, persisting and managing the data between Java objects and the relational database.  It means it went through the Java Community Process.  Its specification # is JSR338 (https://jcp.org/en/jsr/detail?id=338)  Following are implementation of JPA: 1)Eclipse Link 2) Hibernate 3)Open JPA  These are interchangeable or no vendor locking.
  • 14.
    Hibernate Setup We willbe using Hibernate version 4.3.7 in this training and you can get from below link: http://hibernate.org/orm/downloads Hibernate JBOSS Tool for Eclipse: http://download.jboss.org/jbosstools/updates/stable/lu na/
  • 15.
    Basic Setup forHibernate 1. Create Java SE/EE Project. 2. Create Hibernate configuration file. Note: more about this configuration file in next slide 3. Create Java Bean/ Class (Persistent Class).Note: more about this class in next slide 4. Create Mapping File of that Class. 5. Map this class in Hibernate Configuration file.
  • 16.
    Hibernate Configuration Properties hibernate.use_sql_comments:true /false (true means show, false means don’t) hibernate.format_sql: Pretty print the SQL in the log and console. e.g. true | false hibernate.dialect: The classname of a Hibernate org.hibernate.dialect.Dialect which allows Hibernate to generate SQL optimized for a particular relational database.e.g. full.classname.of.Dialect hibernate.show_sql: Write all SQL statements to console. This is an alternative to setting the log category org.hibernate.SQL to debug. e.g. true | false hibernate.default_schema: Qualify unqualified table names with the given schema/tablespace in generated SQL. e.g. SCHEMA_NAME hibernate.hbm2ddl.auto: Automatically validates or exports schema DDL to the database when the SessionFactory is created. With create-drop, the database schema will be dropped when the SessionFactory is closed explicitly. e.g. validate | update | create | create-drop
  • 17.
    Following rules mustbe followed when declaring Persistent Class The four main rules of persistent classes :  Implement a no-argument constructor  Provide an identifier property (optional)  Prefer non-final classes (optional)  Declare accessors and mutators for persistent fields (optional) See the Employee class example in code.
  • 18.
  • 19.
    Types of Generatorin Hibernate  Assigned: lets the application assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.  Identity: supports identity columns in DB2, MySQL, MS SQL Server, Sybase and Hypersonic SQL. The returned identifier is of type long, short or int.  Sequence: uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int.  Uuid: uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.  Increment: generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. There are many more classes for generator. Please visit the following site: https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/mapping.html
  • 20.
    What is anEntity  Entity : An entity is something that exists in itself, actually or potentially, concretely or abstractly, physically or not physically (conceptually).
  • 21.
    Attribute A property, ora conclusion of a characteristic of an entity or substance or An attribute is a characteristic of an entity.
  • 22.
    Entity type orValue(Attribute) type Any piece of data can be expressed as entity type or value type:  Entity Types: Entities have a unique identity means exist independently and define their own lifecycle., which stays the same despite of changes in the properties of the object. For example Human, mobile, computer etc.
  • 23.
     Value Types Avalue type do not define their own lifecycle. We say that they are "owned" by something else (specifically an entity) which defines their lifecycle. For Example: name, address, age of Employee, hand of human, nip of a pen, wheel of a car, companies history of an employee etc. Value types are further classified into 3 sub-categories: basic types, composite types and collection types. • Basic Types: age, name, sex of an employee in single value. • Composite types: aggregate values of basic types for i.e. address of employee contain (country , state ,city and street). • Collection types: collection of data for i.e. companies history of an employee, daily activities of an employee.
  • 24.
    Composite Value Typeand its mapping with an Entity “Address” as a composite value type of an employee. Lets see the example of mapping with an entity in code. Collection Value Type and its mapping with an Entity In hibernate always declare a collection variable type by their parent interface. For example Set, List, Map, Collection etc. Because when we get back the collection object from hibernate its type will be change by hibernate. It won’t be the Java HashSet or ArrayList or HashMap, Its type will be in specialized form.
  • 26.
    Uni-directional and Bi-directionalrelationship Uni-directional Bi-directional Recommended approach make relationship bidirectional in class.
  • 27.
    Collection Value Typeas HashSet Example HashSet Properties:  A Set represents a mathematical set.  It is a Collection that, unlike List, does not allow duplicates.  There must not be two elements of a Set, say e1 and e2, such that e1.equals(e2).  The add method of Set returns false if you try to add a duplicate element.  HashSet allows at most one null element.  HashSet is faster than other implementations of Set, TreeSet and LinkedHashSet. Lets see in action the “Employee Activities” as a collection value type of an employee using HashSet in a program.
  • 28.
    Collection Value Typeas ArrayList Example  An ArrayList is an ordered collection  Permits null elements  It is not synchronized Lets see in action the “Past Companies” as a collection value type of an employee using ArrayList in a program.
  • 29.
    Collection Value Typeas HashMap Example  No guarantees as to the order of the map.  Uniqueness guarantee.  No guarantee that the order will remain constant.  It is unsynchronized and permits nulls. Lets see HashMap collection value type in an action using “Employee Roles” in a program.
  • 30.
    What's Next Next wewill do Entity relationship.  One-to-one  One-to-many  Many-to-one
  • 31.

Editor's Notes

  • #4 http://www.bbc.com/future/story/20140505-secrets-behind-the-big-sleep
  • #10 Persistent means that the object has been saved to the database whereas transient means that it hasn't been saved yet. So for example when you get an entity from a repository, that entity is persistent. When you create a new entity, it is transient until persisted. Transient Object: A new instance of a persistent class which is not associated with a Session, has no representation in the database and no identifier value is considered transient by Hibernate. Only available when the JVM is running Person person = new Person(); person.setName("Foobar"); Persist Object: A persistent instance has a representation in the database, an identifier value and is associated with a Session. You can make a transient instance persistent by associating it with a Session Long id = (Long) session.save(person); JNDI: The Java Naming and Directory Interface (JNDI) is a Java API for a directory service that allows Java software clients to discover and look up data and objects via a name. JDBC: JDBC is a Java API that can access any kind of tabular data, especially data stored in a Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. JTA: JTA is a standard for transactions, allowing for management of multiple transactions among multiple databases. JPA: JPA utilizes JDBC for database connections and SQL-related operations, and -optionally- utilizes JTA for delegating distributed transaction management details to it. Think of JPA as the guidelines that must be followed or an interface, while Hibernate's JPA implementation is code that meets the API as defined by the JPA specification
  • #18 4.1.1. Implement a no-argument constructor All persistent classes must have a default constructor (which can be non-public) so that Hibernate can instantiate them using Constructor.newInstance(). It is recommended that you have a default constructor with at least package visibility for runtime proxy generation in Hibernate. 4.1.2. Provide an identifier property (optional) Cat has a property called id. This property maps to the primary key column of a database table. The property might have been called anything, and its type might have been any primitive type, any primitive "wrapper" type, java.lang.String or java.util.Date. If your legacy database table has composite keys, you can use a user-defined class with properties of these types (see the section on composite identifiers later in the chapter.) The identifier property is strictly optional. You can leave them off and let Hibernate keep track of object identifiers internally. We do not recommend this, however. In fact, some functionality is available only to classes that declare an identifier property: We recommend that you declare consistently-named identifier properties on persistent classes and that you use a nullable (i.e., non-primitive) type. 4.1.3. Prefer non-final classes (optional) A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods. You can persist final classes that do not implement an interface with Hibernate. You will not, however, be able to use proxies for lazy association fetching which will ultimately limit your options for performance tuning. You should also avoid declaring public final methods on the non-final classes. If you want to use a class with a public final method, you must explicitly disable proxying by setting lazy="false". 4.1.4. Declare accessors and mutators for persistent fields (optional) Cat declares accessor methods for all its persistent fields. Many other ORM tools directly persist instance variables. It is better to provide an indirection between the relational schema and internal data structures of the class. By default, Hibernate persists JavaBeans style properties and recognizes method names of the form getFoo, isFoo and setFoo. If required, you can switch to direct field access for particular properties. Properties need not be declared public - Hibernate can persist a property with a default, protected or privateget / set pair.
  • #23 Employee & Employee Address Computer of compaq IBM vs Processor of Intel Car vs Car Engine.
  • #25 8.1. Dependent objects 8.2. Collections of dependent objects 8.3. Components as Map indices 8.4. Components as composite identifiers 8.5. Dynamic components http://www.xyzws.com/javafaq/why-always-override-hashcode-if-overriding-equals/20 http://eclipsesource.com/blogs/2012/09/04/the-3-things-you-should-know-about-hashcode/