SlideShare a Scribd company logo
1 of 51
1
By Shaharyar Khan
shaharyar.khan555@gmail.com
 If you have completed 2 versions of your product and the
product is now stable , working great without any mess up
and then
one day your user ask you to remove mySQL from
backend and use Oracle as I am thinking that this is
more good and efficient
2
Everyone knows that this will be like a bomb on the head of developers
Because it is possible but while doing this developers can suicide due
to extreme bugs in code, massive conversions of queries and may be
DB design
(For instance oracle supports foreign key but mySQL doesn’t).
shaharyar.khan555@gmail.com
 So , there should be a mechanism or a smart API which
provide us a layer between Database and code
 This layer purpose is to interact with DB and our logical
layer should have no concern or have no direct interaction
with Databases.
 So when we want to change our backend then nothing will
be changed and we can save our a lot of time.
3
shaharyar.khan555@gmail.com
 Basically Hibernate purpose is to cater this
 But not only this , Hibernate also provide us ORM
4
Developers Red Hat
Stable release
4.1.4 Final / May 31, 2012 (some days
ago)
Development status Active
Written in Java
Operating system Cross-platform (JVM)
Platform Java Virtual Machine
Type Object-relational mapping
License GNU Lesser General Public License
Website www.hibernate.org
shaharyar.khan555@gmail.com
 While working with hibernate , you can bump with these
words which are the basic part of Hibernate
ORM
Mapping
Persistence
And may be
HQL
5
shaharyar.khan555@gmail.com
 Data management tasks in object-oriented (OO)
programming are typically implemented by manipulating
objects
 consider an address book entry that represents a single
person along with zero or more phone numbers and zero or
more addresses. This could be modeled in an object-oriented
implementation by a "Person object" with attributes/fields to
hold each data item that the entry comprises: the person's
name, a list of phone numbers, and a list of addresses
 Simply We can say that we are talking about Domain model
 So ,the mapping of domain model into entity relationship
model is called Object relational mapping or ORM
6
shaharyar.khan555@gmail.com
 For ORM , We map JAVA classes into database tables
 It is accomplished through the configuration of an XML file
or by using Java Annotations
 Hibernate can use the XML file or the annotations to
maintain the database schema
 Facilities to arrange one-to-many and many-to-many & all
other relationships between classes are provided
7
shaharyar.khan555@gmail.com
 Hibernate provides transparent persistence for Plain Old
Java Objects(POJOs)
 The only strict requirement for a persistent class is a no-
argument constructor, not necessarily public
 Collections of data objects are typically stored in Java
collection objects such as Set and List
 Hibernate can be configured to lazy load associated
collections. Lazy loading is the default as of Hibernate 3
8
shaharyar.khan555@gmail.com
 Hibernate provides an SQL inspired language called
Hibernate Query Language (HQL)
 It allows SQL-like queries to be written against Hibernate's
data objects
 Criteria Queries are provided as an object-oriented alternative
to HQL
9
shaharyar.khan555@gmail.com
10
 A “virtual object database” is created that can be used from
within the programming language
shaharyar.khan555@gmail.com
 Previous diagram shows minimal architecture of Hibernate
 It creates a layer between Database and the Application
 It loads the configuration details like Database connection
string, entity classes, mappings etc
 Hibernate creates persistent objects which synchronize data
between application and database
 Let see this architecture in detail diagram
11
shaharyar.khan555@gmail.com
 The above diagram shows a comprehensive architecture of
Hibernate
12
shaharyar.khan555@gmail.com
 In order to persist data to a database, Hibernate create an
instance of entity class (Java class mapped with database
table)
 This object is called Transient object as they are not yet
associated with the session or not yet persisted to a database
 To persist the object to database, the instance of
SessionFactory interface is created. SessionFactory is a
singleton instance which implements Factory design pattern
 SessionFactory loads hibernate.cfg.xml file (Hibernate
configuration file) and with the help of TransactionFactory
and ConnectionProvider implements all the configuration
settings on a database
13
shaharyar.khan555@gmail.com
 Each database connection in Hibernate is created by creating
an instance of Session interface
 Session represents a single connection with database
 Session objects are created from SessionFactory object
 Hibernate also provides built-in Transaction APIs which
abstracts away the application from underlying JDBC or JTA
transaction
 Each transaction represents a single atomic unit of work
 One Session can span through multiple transactions.
14
shaharyar.khan555@gmail.com
 Before starting any example , We should know about some
configuration files
 These files are needed for mapping and to load many other
properties and create database connection
 Hibernate provide following type of configurtions:
hibernate.cfg.xml – A standard XML file which contains hibernate
configuration like database connection, class mappings etc and which
resides in root of application’s CLASSPATH
hibernate.properties: A Java compliant property file which holds
key value pair for different hibernate configuration strings
Programmatic configuration: This is the manual approach. The
configuration can be defined in Java class
15
shaharyar.khan555@gmail.com
16
 <hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">
jdbc:mysql://localhost/EmployeeDB</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">10</property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping files -->
<mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
shaharyar.khan555@gmail.com
 Once the hibernate.cfg.xml file is created and placed in root
of application’s CLASSPATH, the same can be loaded in
Hibernate using following API
SessionFactory sessionFactory = new
Configuration().configure().buildSessionFactory();
17
This above code will load default hibernate.cfg.xml file and
all the configuration mentioned in it
In case you want to override default naming convention and
want to have your own configuration file like
“employeedb.cfg.xml”, following API can be used:
SessionFactory sf = new Configuration().configure("employeedb.cfg.xml")
     .buildSessionFactory()
shaharyar.khan555@gmail.com
hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url= jdbc:mysql://localhost:3306/employeeDB
hibernate.connection.username=root
hibernate.connection.password=
hibernate.dialect = org.hibernate.dialect.MySQLDialect
hibernate.connection.pool_size=1 // C3P0(open source JDBC
// connection pool
//distributed along with
//Hibernate in the lib
//directory)
Note: Both hibernate.cfg.xml and hibernate.properties files can be provided
simultaneously in an application. In this case hibernate.cfg.xml gets precedence
over hibernate.properties.
18
shaharyar.khan555@gmail.com
 We can obtain a org.hibernate.cfg.Configuration instance by
instantiating it directly and specifying XML mapping
documents. If the mapping files are in the classpath, use
addResource().
Configuration cfg = new Configuration()
     .addResource("Employee.hbm.xml")
     .addResource("Department.hbm.xml");
19
An alternative way is to specify the mapped class and allow
Hibernate to find the mapping document for you
Configuration cfg = new Configuration()
    .addClass(com.deltasoft.hibernate.Employee.class)
    .addClass(com.deltasoft.hibernate.Department.class);
Hibernate will then search for mapping files named
/com/deltasoft/hibernate/Employee.hbm.xml and
/com/deltasoft/hibernate/Department.hbm.xml in the classpath. This approach
eliminates any hardcoded filenames.
shaharyar.khan555@gmail.com
 A org.hibernate.cfg.Configuration also allows you to specify
configuration properties
Configuration cfg = new Configuration()
.addClass(com.deltasoft.hibernate.Employee.class)
.addClass(com.deltasoft.hibernate.Department.class)
.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect")
.setProperty(" hibernate.connection.url ", " jdbc:mysql://localhost/EmployeeDB
")
.setProperty("hibernate.order_updates", "true");
20
shaharyar.khan555@gmail.com
 Let see in this example that how can we insert record in
MySQL database using Hibernate
 In this example , We will create a contact objecta and save it
in Database ……
21
shaharyar.khan555@gmail.com
public class Contact {
  private String firstName;
  private String lastName;
  private String email;
  private long id; //Contact.java
//This is a POJO class
  public String getEmail() {
  return email;
  }
  public String getFirstName() { //We Can Assume that contact is an entity and these all
  return firstName; // are attributes of contact
  }
  public String getLastName() {
  return lastName;
  }
  public void setEmail(String string) {
  email = string;
  }
  public void setFirstName(String string) {
  firstName = string;
  }
  public void setLastName(String string) {
  lastName = string;
  }
  public long getId() {
  return id;
  }
 public void setId(long l) {
  id = l;
  }
} 22
shaharyar.khan555@gmail.com
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class FirstExample {
  public static void main(String[] args) {
  Session session = null;
//FirstExample.java
  try{
  // This step will read hibernate.cfg.xml  and prepare hibernate for use
  SessionFactory sessionFactory = new  Configuration().configure().buildSessionFactory();
 session =sessionFactory.openSession();
  //Create new instance of Contact and set  values in it by reading them from form object
 System.out.println("Inserting Record");
  Contact contact = new Contact();
  contact.setId(3);
  contact.setFirstName(“Shaharyar");
  contact.setLastName("Khan");
  contact.setEmail(“shaharyarkhan@deltasoft.com.pk");
  session.save(contact);
  System.out.println("Done"); //same as we have update() , delete() methods
  }catch(Exception e){
  System.out.println(e.getMessage());
  }finally{
  // Actual contact insertion will happen at this step
  session.flush();
  session.close(); 23
shaharyar.khan555@gmail.com
?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
  <property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver</property>
  <property name="hibernate.connection.url">
jdbc:mysql://localhost/EmployeeDB</property>
  <property name="hibernate.connection.username">root</property>
  <property name="hibernate.connection.password"></property>
  <property name="hibernate.connection.pool_size">10</property>
  <property name="show_sql">true</property>
  <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="hibernate.hbm2ddl.auto">update</property>
  <!-- Mapping files -->
  <mapping resource="contact.hbm.xml"/>
</session-factory>
</hibernate-configuration>
24
shaharyar.khan555@gmail.com
 In the above configuration file we specified to use the “EmployeeDB"
which is running on localhost and the user of the database is root with
no password. The dialect property  is
org.hibernate.dialect.MySQLDialect which tells the Hibernate that we
are using MySQL Database.
25
DB2 - org.hibernate.dialect.DB2Dialect
HypersonicSQL - org.hibernate.dialect.HSQLDialect
Informix - org.hibernate.dialect.InformixDialect
Ingres - org.hibernate.dialect.IngresDialect
PostgreSQL - org.hibernate.dialect.PostgreSQLDialect
Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect
MySQL - org.hibernate.dialect.MySQLDialect
Oracle (any version) - org.hibernate.dialect.OracleDialect
Oracle 9 - org.hibernate.dialect.Oracle9Dialect
Progress - org.hibernate.dialect.ProgressDialect
SAP DB - org.hibernate.dialect.SAPDBDialect
Sybase - org.hibernate.dialect.SybaseDialect
Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect
Some dialects of
different
databases
shaharyar.khan555@gmail.com
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name=“com .deltasoft.hibernate.Contact" table="CONTACT">
   <id name="id" type="long" column="ID" >
   <generator class="assigned"/>
  </id>
  <property name="firstName">
   <column name="FIRSTNAME" />
  </property>
  <property name="lastName">
  <column name="LASTNAME"/>
  </property>
  <property name="email">
  <column name="EMAIL"/>
  </property>
 </class>
</hibernate-mapping>
26
shaharyar.khan555@gmail.com
27
It is better to get these jar files like this
 Go to http://sourceforge.net/projects/hibernate/files/
 Click on Download hibernate-search-4.1.1.Final-dist.zip (31.0 MB)
 Now a folder will be downloaded on your machine.
 Extract the folder and in extracted folder you will see a folder
“required” placed in “hibernate-search-
4.1.1.Final/dist/lib/required”
 Copy all the jar files present in “required” folder into your classpath
shaharyar.khan555@gmail.com
 <hibernate-mapping> element
The first or root element of hibernate mapping document is <hibernate-mapping> element.
Between the <hibernate-mapping> tag class element(s) are present
28
 <class> element
The <Class> element maps the class object with corresponding entity in the database. It also
tells what table in the database has to access and what column in that table it should use. Within one
<hibernate-mapping> element, several <class> mappings are possible
<id> element
The <id> element in unique identifier to identify and object. In fact <id> element map
with the primary key of the table. In our code :
<id name="id" type="long" column="ID" >
primary key maps to the ID field of the table CONTACT. The attributes of the id
element are:
name: The property name used by the persistent class.
column: The column used to store the primary key value.
type: The Java data type used.
unsaved-value: This is the value used to determine if a class has been made
persistent. If the value of the id attribute is null, then it means that
this object has not been persisted.
shaharyar.khan555@gmail.com
 <generator> element
The <generator> method is used to generate the primary key for the new
record. Here is some of the commonly used generators :
 
Increment - This is used to generate primary keys of type long, short or int that are unique
only. It should not be used in the clustered deployment environment.
 
Sequence - Hibernate can also use the sequences to generate the primary key. It can be used
with DB2, PostgreSQL, Oracle, SAP DB databases.
  
Assigned - Assigned method is used when application code generates the primary key. 
29
 <property> element
The property elements define standard Java attributes and their mapping
into database schema. The property element supports the column child
element to specify additional properties, such as the index name on a
column or a specific column type
shaharyar.khan555@gmail.com
 Same like JSF and other frameworks of java , Hibernate also
supports annotations
 Now if we want to transfer our previous contact example
into annotations then we havn’t need “contact.hbm.xml” so
delete this if you want to introduce annotations in your code
 Now our Contact.java would be like this
30
shaharyar.khan555@gmail.com
31
@Entity
@Table(name="EMPLOYEE")
public class Contact {
@Id
  @GeneratedValue  
private long id; //Contact.java with annotations
@Column(name="firstname“)
private String firstName;
@Column(name=“lastname“)
  private String lastName;
@Column(name=“email“)
  private String email;
  
//getter and setters
}
    
shaharyar.khan555@gmail.com
32
 Now in FirstExample.java just change this line
SessionFactory sessionFactory = new  Configuration().configure().
buildSessionFactory();
TO
SessionFactory sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
And in hibernate.cfg.xml change this
<mappingresource="net/viralpatel/hibernate/Employee.hbm.xml"/>
TO
<mapping class=“com.deltasoft.hibernate.Employee"/>
shaharyar.khan555@gmail.com
33
We will discuss some these relations in our this session
shaharyar.khan555@gmail.com
34
 Lets take an example that
 Employee has a one to one relation with EmployeeDetail
 So, First we create a Employee class and then EmployeeDetail in which
we map them by annotations
shaharyar.khan555@gmail.com
 
@Entity
@Table(name="EMPLOYEE")
public class Employee {
 
    @Id
    @GeneratedValue
    @Column(name="employee_id")
    private Long employeeId;
     
    @Column(name="firstname")
    private String firstname;
     
    @Column(name="lastname")
    private String lastname;
     
    @Column(name="birth_date")
    private Date birthDate;
     
    @Column(name="cell_phone")
    private String cellphone;
 
    @OneToOne(mappedBy="employee", cascade=CascadeType.ALL)
    private EmployeeDetail employeeDetail;
     
    public Employee() {
         
    }
     
    public Employee(String firstname, String lastname, Date birthdate, String phone) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.birthDate = birthdate;
        this.cellphone = phone;
         
    }
 
    // Getter and Setter methods
}
35
shaharyar.khan555@gmail.com
<?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>
        <!-- Database connection settings -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/tutorial</property>
        <property name="connection.username">root</property>
        <property name="connection.password"></property>
         
        <property name="connection.pool_size">1</property>
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        <property name="current_session_context_class">thread</property>
        <property
name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
        <property name="show_sql">true</property>
        <property name="hbm2ddl.auto">validate</property>
  
    <mapping class="net.viralpatel.hibernate.EmployeeDetail"/>
    <mapping class="net.viralpatel.hibernate.Employee"/>
          
    </session-factory> 36
shaharyar.khan555@gmail.com
public class Main {
 
     public static void main(String[] args) {
 
        System.out.println("Hibernate One-To-One example (Annotation)");
         
        SessionFactory sf = = new AnnotationConfiguration().configure()
                    .buildSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
 
        EmployeeDetail employeeDetail = new EmployeeDetail("10th Street", "LA", "San
Francisco", "U.S.");
         
        Employee employee = new Employee(“Ali", “Asim", new Date(121212),
                "114-857-965");
        employee.setEmployeeDetail(employeeDetail);
        employeeDetail.setEmployee(employee);
         
         
        session.save(employee);
 
    }
37
shaharyar.khan555@gmail.com
38
Department.java
shaharyar.khan555@gmail.com
@Entity
@Table(name="EMPLOYEE")
public class Employee {
 
    @Id
    @GeneratedValue
    @Column(name="employee_id")
    private Long employeeId;
     
    @Column(name="firstname")
    private String firstname;
     
    @Column(name="lastname")
    private String lastname;
     
    @Column(name="birth_date")
    private Date birthDate;
     
    @Column(name="cell_phone")
    private String cellphone;
 
    @ManyToOne
    @JoinColumn(name="department_id")
    private Department department;
     
    public Employee() {
         
    }
     
    public Employee(String firstname, String lastname, String phone) {
        this.firstname = firstname;
        this.lastname = lastname;
        this.birthDate = new Date(System.currentTimeMillis());
        this.cellphone = phone;
    }
    // Getter and Setter methods
}
39
shaharyar.khan555@gmail.com
 public class Main {
 
    @SuppressWarnings("unchecked")
    public static void main(String[] args) {
 
        SessionFactory sf = = new AnnotationConfiguration().configure()
                    .buildSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
 
        Department department = new Department();
        department.setDepartmentName("Sales");
        session.save(department);
         
        Employee emp1 = new Employee("Nina", "Mayers", "111");
        Employee emp2 = new Employee("Tony", "Almeida", "222");
 
        emp1.setDepartment(department);
        emp2.setDepartment(department);
         
        session.save(emp1);
        session.save(emp2);
 
        session.getTransaction().commit();
        session.close();
    }
} 40
shaharyar.khan555@gmail.com
41
 Many Employees have many Meetings
So
 We will Map Employee class with meeting class
shaharyar.khan555@gmail.com
42
@Entity
@Table(name="EMPLOYEE")
public class Employee {
     
    @Id
    @Column(name="EMPLOYEE_ID")
    @GeneratedValue
    private Long employeeId;
     
    @Column(name="FIRSTNAME")
    private String firstname;
     
    @Column(name="LASTNAME")
    private String lastname;
     
    @ManyToMany(cascade = {CascadeType.ALL})
    @JoinTable(name="EMPLOYEE_MEETING",
                joinColumns={@JoinColumn(name="EMPLOYEE_ID")},
                inverseJoinColumns={@JoinColumn(name="MEETING_ID")})
    private Set<Meeting> meetings = new HashSet<Meeting>();
     
    public Employee() {
    }
    public Employee(String firstname, String lastname) {
        this.firstname = firstname;
        this.lastname = lastname;
    }    
    // Getter and Setter methods
}
shaharyar.khan555@gmail.com
@Entity
@Table(name="MEETING")
public class Meeting {
 
    @Id
    @Column(name="MEETING_ID")
    @GeneratedValue
    private Long meetingId;
 
    @Column(name="SUBJECT")
    private String subject;
     
    @Column(name="MEETING_DATE")
    private Date meetingDate;
     
    @ManyToMany(mappedBy="meetings")
    private Set<Employee> employees = new HashSet<Employee>();
     
    public Meeting(String subject) {
        this.subject = subject;
        this.meetingDate = new Date();
    }
     
    // Getter and Setter methods
}
43
shaharyar.khan555@gmail.com
44
public class Main {
  
    public static void main(String[] args) {
  
        SessionFactory sf = new AnnotationConfiguration().configure()
                    .buildSessionFactory();
        Session session = sf.openSession();
        session.beginTransaction();
  
         
        Meeting meeting1 = new Meeting("Quaterly Sales meeting");
        Meeting meeting2 = new Meeting("Weekly Status meeting");
         
        Employee employee1 = new Employee("Sergey", "Brin");
        Employee employee2 = new Employee("Larry", "Page");
 
        employee1.getMeetings().add(meeting1);
        employee1.getMeetings().add(meeting2);
        employee2.getMeetings().add(meeting1);
         
        session.save(employee1);
        session.save(employee2);
         
        session.getTransaction().commit();
        session.close();
    }
}
shaharyar.khan555@gmail.com
 Hibernate Query Language or HQL for short is extremely
powerful query language
 HQL is much like SQL  and are case-insensitive, except for
the names of the Java Classes and properties
 Hibernate Query Language is used to execute queries against
database
 Hibernate automatically generates the sql query and execute
it against underlying database if HQL is used in the
application.
 Hibernate Query Language uses Classes and properties
instead of tables and columns.
45
shaharyar.khan555@gmail.com
46
 Subqueries
Subqueries are nothing but its a query within another query. Hibernate
supports Subqueries if the underlying database supports it.
shaharyar.khan555@gmail.com
 //Using from Clause
  
String SQL_QUERY ="from Insurance insurance";
 
 Query query = session.createQuery(SQL_QUERY);
  
for(Iterator it=query.iterate();it.hasNext();){
Insurance insurance=(Insurance)it.next();
 System.out.println("ID: " + 
insurance.getLngInsuranceId());
 System.out.println("First
Name: " + insurance.getInsuranceName());
  }
47
shaharyar.khan555@gmail.com
String SQL_QUERY ="Select insurance.
lngInsuranceId,insurance.insuranceName," + 
 "insurance.investementAmount,insurance.
investementDate from Insurance insurance";
 Query query = session.createQuery(SQL_QUERY);
 for(Iterator it=query.iterate();it.hasNext();){
 Object[] row = (Object[]) it.next();
 System.out.println("ID: " + row[0]);
 System.out.println("Name: " + row[1]);
 System.out.println("Amount: " + row[2]);
 }
It returns resultset in form of objects
48
shaharyar.khan555@gmail.com
String SQL_QUERY =" from Insurance
as insurance where insurance.lngInsuranceId='1'";
Query query = session.createQuery
(SQL_QUERY);
//remaining code
49
shaharyar.khan555@gmail.com
String SQL_QUERY = "select avg
(investementAmount) from Insurance insurance";
Query query = sess.createQuery(SQL_QUERY);
List list = query.list();
System.out.println("Average of 
Invested Amount: " + list.get(0));
__________________________________________________
String SQL_QUERY = "select 
max(investementAmount)from Insurance insurance";
Query query = sess.createQuery(SQL_QUERY);
List list = query.list();
System.out.println("Max Invested Amount: " + list.get(0);
50
avg(..) usage
max(…
)
usage
shaharyar.khan555@gmail.com
51
shaharyar.khan555@gmail.com

More Related Content

What's hot

Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaEdureka!
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentalsMadhuri Kavade
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architectureAnurag
 
Oracle developer interview questions(entry level)
Oracle developer interview questions(entry level)Oracle developer interview questions(entry level)
Oracle developer interview questions(entry level)Naveen P
 
Oracle to vb 6.0 connectivity
Oracle to vb 6.0 connectivityOracle to vb 6.0 connectivity
Oracle to vb 6.0 connectivityrohit vishwakarma
 
Ob loading data_oracle
Ob loading data_oracleOb loading data_oracle
Ob loading data_oracleSteve Xu
 
.NET Core, ASP.NET Core Course, Session 11
.NET Core, ASP.NET Core Course, Session 11.NET Core, ASP.NET Core Course, Session 11
.NET Core, ASP.NET Core Course, Session 11aminmesbahi
 
Configuring jpa in a Spring application
Configuring jpa in a  Spring applicationConfiguring jpa in a  Spring application
Configuring jpa in a Spring applicationJayasree Perilakkalam
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14aminmesbahi
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12Sisir Ghosh
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplateGuo Albert
 

What's hot (20)

Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
Hibernate Interview Questions | Edureka
Hibernate Interview Questions | EdurekaHibernate Interview Questions | Edureka
Hibernate Interview Questions | Edureka
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Oracle developer interview questions(entry level)
Oracle developer interview questions(entry level)Oracle developer interview questions(entry level)
Oracle developer interview questions(entry level)
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Oracle to vb 6.0 connectivity
Oracle to vb 6.0 connectivityOracle to vb 6.0 connectivity
Oracle to vb 6.0 connectivity
 
Ob loading data_oracle
Ob loading data_oracleOb loading data_oracle
Ob loading data_oracle
 
.NET Core, ASP.NET Core Course, Session 11
.NET Core, ASP.NET Core Course, Session 11.NET Core, ASP.NET Core Course, Session 11
.NET Core, ASP.NET Core Course, Session 11
 
Spring & hibernate
Spring & hibernateSpring & hibernate
Spring & hibernate
 
Spring database - part2
Spring database -  part2Spring database -  part2
Spring database - part2
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Configuring jpa in a Spring application
Configuring jpa in a  Spring applicationConfiguring jpa in a  Spring application
Configuring jpa in a Spring application
 
.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14.NET Core, ASP.NET Core Course, Session 14
.NET Core, ASP.NET Core Course, Session 14
 
ASP.NET Session 11 12
ASP.NET Session 11 12ASP.NET Session 11 12
ASP.NET Session 11 12
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
Data access
Data accessData access
Data access
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Spring jdbc dao
Spring jdbc daoSpring jdbc dao
Spring jdbc dao
 
Spring JDBCTemplate
Spring JDBCTemplateSpring JDBCTemplate
Spring JDBCTemplate
 

Viewers also liked

Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationKhoa Nguyen
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Trainingsourabh aggarwal
 
Hibernate
HibernateHibernate
HibernateAjay K
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernatepatinijava
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernatehr1383
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesecosio GmbH
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016Vlad Mihalcea
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentationManav Prasad
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To HibernateAmit Himani
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate FrameworkRaveendra R
 

Viewers also liked (15)

Hibernate Basic Concepts - Presentation
Hibernate Basic Concepts - PresentationHibernate Basic Concepts - Presentation
Hibernate Basic Concepts - Presentation
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Hibernate complete Training
Hibernate complete TrainingHibernate complete Training
Hibernate complete Training
 
Hibernate
HibernateHibernate
Hibernate
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Hibernate
HibernateHibernate
Hibernate
 
Patni Hibernate
Patni   HibernatePatni   Hibernate
Patni Hibernate
 
Introduction to hibernate
Introduction to hibernateIntroduction to hibernate
Introduction to hibernate
 
Hibernate in Nutshell
Hibernate in NutshellHibernate in Nutshell
Hibernate in Nutshell
 
Introduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examplesIntroduction to JPA and Hibernate including examples
Introduction to JPA and Hibernate including examples
 
High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016High-Performance Hibernate Devoxx France 2016
High-Performance Hibernate Devoxx France 2016
 
Hibernate presentation
Hibernate presentationHibernate presentation
Hibernate presentation
 
Intro To Hibernate
Intro To HibernateIntro To Hibernate
Intro To Hibernate
 
Introduction to Hibernate Framework
Introduction to Hibernate FrameworkIntroduction to Hibernate Framework
Introduction to Hibernate Framework
 
Introduction to Advanced Javascript
Introduction to Advanced JavascriptIntroduction to Advanced Javascript
Introduction to Advanced Javascript
 

Similar to Hibernate

Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggetsVirtual Nuggets
 
Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphonyBrahampal Singh
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvcGuo Albert
 
12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptxFaezNasir
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_entechbed
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questionsDhiraj Champawat
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking TourJoshua Long
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetJayarajus
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginnersRahul Jain
 

Similar to Hibernate (20)

Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
 
Hibernate
HibernateHibernate
Hibernate
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
 
Hibernate
HibernateHibernate
Hibernate
 
Play 2.0
Play 2.0Play 2.0
Play 2.0
 
Drupal 8 meets to symphony
Drupal 8 meets to symphonyDrupal 8 meets to symphony
Drupal 8 meets to symphony
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Hibernate tutorial
Hibernate tutorialHibernate tutorial
Hibernate tutorial
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Toms introtospring mvc
Toms introtospring mvcToms introtospring mvc
Toms introtospring mvc
 
12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx12_Data_Storage_Part_2.pptx
12_Data_Storage_Part_2.pptx
 
What is struts_en
What is struts_enWhat is struts_en
What is struts_en
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Synopsis
SynopsisSynopsis
Synopsis
 
What is hibernate?
What is hibernate?What is hibernate?
What is hibernate?
 
Spring 3.1: a Walking Tour
Spring 3.1: a Walking TourSpring 3.1: a Walking Tour
Spring 3.1: a Walking Tour
 
TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U6
 
Hibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ NizampetHibernate training at HarshithaTechnologySolutions @ Nizampet
Hibernate training at HarshithaTechnologySolutions @ Nizampet
 
Hibernate 18052012
Hibernate 18052012Hibernate 18052012
Hibernate 18052012
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 

Recently uploaded

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
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
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
 
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
 
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
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
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
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Hyundai Motor Group
 
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
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
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
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 

Recently uploaded (20)

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
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
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
 
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
 
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 ...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
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
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2Next-generation AAM aircraft unveiled by Supernal, S-A2
Next-generation AAM aircraft unveiled by Supernal, S-A2
 
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
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
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
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 

Hibernate

  • 2.  If you have completed 2 versions of your product and the product is now stable , working great without any mess up and then one day your user ask you to remove mySQL from backend and use Oracle as I am thinking that this is more good and efficient 2 Everyone knows that this will be like a bomb on the head of developers Because it is possible but while doing this developers can suicide due to extreme bugs in code, massive conversions of queries and may be DB design (For instance oracle supports foreign key but mySQL doesn’t). shaharyar.khan555@gmail.com
  • 3.  So , there should be a mechanism or a smart API which provide us a layer between Database and code  This layer purpose is to interact with DB and our logical layer should have no concern or have no direct interaction with Databases.  So when we want to change our backend then nothing will be changed and we can save our a lot of time. 3 shaharyar.khan555@gmail.com
  • 4.  Basically Hibernate purpose is to cater this  But not only this , Hibernate also provide us ORM 4 Developers Red Hat Stable release 4.1.4 Final / May 31, 2012 (some days ago) Development status Active Written in Java Operating system Cross-platform (JVM) Platform Java Virtual Machine Type Object-relational mapping License GNU Lesser General Public License Website www.hibernate.org shaharyar.khan555@gmail.com
  • 5.  While working with hibernate , you can bump with these words which are the basic part of Hibernate ORM Mapping Persistence And may be HQL 5 shaharyar.khan555@gmail.com
  • 6.  Data management tasks in object-oriented (OO) programming are typically implemented by manipulating objects  consider an address book entry that represents a single person along with zero or more phone numbers and zero or more addresses. This could be modeled in an object-oriented implementation by a "Person object" with attributes/fields to hold each data item that the entry comprises: the person's name, a list of phone numbers, and a list of addresses  Simply We can say that we are talking about Domain model  So ,the mapping of domain model into entity relationship model is called Object relational mapping or ORM 6 shaharyar.khan555@gmail.com
  • 7.  For ORM , We map JAVA classes into database tables  It is accomplished through the configuration of an XML file or by using Java Annotations  Hibernate can use the XML file or the annotations to maintain the database schema  Facilities to arrange one-to-many and many-to-many & all other relationships between classes are provided 7 shaharyar.khan555@gmail.com
  • 8.  Hibernate provides transparent persistence for Plain Old Java Objects(POJOs)  The only strict requirement for a persistent class is a no- argument constructor, not necessarily public  Collections of data objects are typically stored in Java collection objects such as Set and List  Hibernate can be configured to lazy load associated collections. Lazy loading is the default as of Hibernate 3 8 shaharyar.khan555@gmail.com
  • 9.  Hibernate provides an SQL inspired language called Hibernate Query Language (HQL)  It allows SQL-like queries to be written against Hibernate's data objects  Criteria Queries are provided as an object-oriented alternative to HQL 9 shaharyar.khan555@gmail.com
  • 10. 10  A “virtual object database” is created that can be used from within the programming language shaharyar.khan555@gmail.com
  • 11.  Previous diagram shows minimal architecture of Hibernate  It creates a layer between Database and the Application  It loads the configuration details like Database connection string, entity classes, mappings etc  Hibernate creates persistent objects which synchronize data between application and database  Let see this architecture in detail diagram 11 shaharyar.khan555@gmail.com
  • 12.  The above diagram shows a comprehensive architecture of Hibernate 12 shaharyar.khan555@gmail.com
  • 13.  In order to persist data to a database, Hibernate create an instance of entity class (Java class mapped with database table)  This object is called Transient object as they are not yet associated with the session or not yet persisted to a database  To persist the object to database, the instance of SessionFactory interface is created. SessionFactory is a singleton instance which implements Factory design pattern  SessionFactory loads hibernate.cfg.xml file (Hibernate configuration file) and with the help of TransactionFactory and ConnectionProvider implements all the configuration settings on a database 13 shaharyar.khan555@gmail.com
  • 14.  Each database connection in Hibernate is created by creating an instance of Session interface  Session represents a single connection with database  Session objects are created from SessionFactory object  Hibernate also provides built-in Transaction APIs which abstracts away the application from underlying JDBC or JTA transaction  Each transaction represents a single atomic unit of work  One Session can span through multiple transactions. 14 shaharyar.khan555@gmail.com
  • 15.  Before starting any example , We should know about some configuration files  These files are needed for mapping and to load many other properties and create database connection  Hibernate provide following type of configurtions: hibernate.cfg.xml – A standard XML file which contains hibernate configuration like database connection, class mappings etc and which resides in root of application’s CLASSPATH hibernate.properties: A Java compliant property file which holds key value pair for different hibernate configuration strings Programmatic configuration: This is the manual approach. The configuration can be defined in Java class 15 shaharyar.khan555@gmail.com
  • 16. 16  <hibernate-configuration> <session-factory> <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url"> jdbc:mysql://localhost/EmployeeDB</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password"></property> <property name="hibernate.connection.pool_size">10</property> <property name="show_sql">true</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.hbm2ddl.auto">update</property> <!-- Mapping files --> <mapping resource="contact.hbm.xml"/> </session-factory> </hibernate-configuration> shaharyar.khan555@gmail.com
  • 17.  Once the hibernate.cfg.xml file is created and placed in root of application’s CLASSPATH, the same can be loaded in Hibernate using following API SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); 17 This above code will load default hibernate.cfg.xml file and all the configuration mentioned in it In case you want to override default naming convention and want to have your own configuration file like “employeedb.cfg.xml”, following API can be used: SessionFactory sf = new Configuration().configure("employeedb.cfg.xml")      .buildSessionFactory() shaharyar.khan555@gmail.com
  • 18. hibernate.connection.driver_class=com.mysql.jdbc.Driver hibernate.connection.url= jdbc:mysql://localhost:3306/employeeDB hibernate.connection.username=root hibernate.connection.password= hibernate.dialect = org.hibernate.dialect.MySQLDialect hibernate.connection.pool_size=1 // C3P0(open source JDBC // connection pool //distributed along with //Hibernate in the lib //directory) Note: Both hibernate.cfg.xml and hibernate.properties files can be provided simultaneously in an application. In this case hibernate.cfg.xml gets precedence over hibernate.properties. 18 shaharyar.khan555@gmail.com
  • 19.  We can obtain a org.hibernate.cfg.Configuration instance by instantiating it directly and specifying XML mapping documents. If the mapping files are in the classpath, use addResource(). Configuration cfg = new Configuration()      .addResource("Employee.hbm.xml")      .addResource("Department.hbm.xml"); 19 An alternative way is to specify the mapped class and allow Hibernate to find the mapping document for you Configuration cfg = new Configuration()     .addClass(com.deltasoft.hibernate.Employee.class)     .addClass(com.deltasoft.hibernate.Department.class); Hibernate will then search for mapping files named /com/deltasoft/hibernate/Employee.hbm.xml and /com/deltasoft/hibernate/Department.hbm.xml in the classpath. This approach eliminates any hardcoded filenames. shaharyar.khan555@gmail.com
  • 20.  A org.hibernate.cfg.Configuration also allows you to specify configuration properties Configuration cfg = new Configuration() .addClass(com.deltasoft.hibernate.Employee.class) .addClass(com.deltasoft.hibernate.Department.class) .setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLInnoDBDialect") .setProperty(" hibernate.connection.url ", " jdbc:mysql://localhost/EmployeeDB ") .setProperty("hibernate.order_updates", "true"); 20 shaharyar.khan555@gmail.com
  • 21.  Let see in this example that how can we insert record in MySQL database using Hibernate  In this example , We will create a contact objecta and save it in Database …… 21 shaharyar.khan555@gmail.com
  • 22. public class Contact {   private String firstName;   private String lastName;   private String email;   private long id; //Contact.java //This is a POJO class   public String getEmail() {   return email;   }   public String getFirstName() { //We Can Assume that contact is an entity and these all   return firstName; // are attributes of contact   }   public String getLastName() {   return lastName;   }   public void setEmail(String string) {   email = string;   }   public void setFirstName(String string) {   firstName = string;   }   public void setLastName(String string) {   lastName = string;   }   public long getId() {   return id;   }  public void setId(long l) {   id = l;   } } 22 shaharyar.khan555@gmail.com
  • 23. import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class FirstExample {   public static void main(String[] args) {   Session session = null; //FirstExample.java   try{   // This step will read hibernate.cfg.xml  and prepare hibernate for use   SessionFactory sessionFactory = new  Configuration().configure().buildSessionFactory();  session =sessionFactory.openSession();   //Create new instance of Contact and set  values in it by reading them from form object  System.out.println("Inserting Record");   Contact contact = new Contact();   contact.setId(3);   contact.setFirstName(“Shaharyar");   contact.setLastName("Khan");   contact.setEmail(“shaharyarkhan@deltasoft.com.pk");   session.save(contact);   System.out.println("Done"); //same as we have update() , delete() methods   }catch(Exception e){   System.out.println(e.getMessage());   }finally{   // Actual contact insertion will happen at this step   session.flush();   session.close(); 23 shaharyar.khan555@gmail.com
  • 24. ?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory>   <property name="hibernate.connection.driver_class"> com.mysql.jdbc.Driver</property>   <property name="hibernate.connection.url"> jdbc:mysql://localhost/EmployeeDB</property>   <property name="hibernate.connection.username">root</property>   <property name="hibernate.connection.password"></property>   <property name="hibernate.connection.pool_size">10</property>   <property name="show_sql">true</property>   <property name="dialect">org.hibernate.dialect.MySQLDialect</property>   <property name="hibernate.hbm2ddl.auto">update</property>   <!-- Mapping files -->   <mapping resource="contact.hbm.xml"/> </session-factory> </hibernate-configuration> 24 shaharyar.khan555@gmail.com
  • 25.  In the above configuration file we specified to use the “EmployeeDB" which is running on localhost and the user of the database is root with no password. The dialect property  is org.hibernate.dialect.MySQLDialect which tells the Hibernate that we are using MySQL Database. 25 DB2 - org.hibernate.dialect.DB2Dialect HypersonicSQL - org.hibernate.dialect.HSQLDialect Informix - org.hibernate.dialect.InformixDialect Ingres - org.hibernate.dialect.IngresDialect PostgreSQL - org.hibernate.dialect.PostgreSQLDialect Microsoft SQL Server - org.hibernate.dialect.SQLServerDialect MySQL - org.hibernate.dialect.MySQLDialect Oracle (any version) - org.hibernate.dialect.OracleDialect Oracle 9 - org.hibernate.dialect.Oracle9Dialect Progress - org.hibernate.dialect.ProgressDialect SAP DB - org.hibernate.dialect.SAPDBDialect Sybase - org.hibernate.dialect.SybaseDialect Sybase Anywhere - org.hibernate.dialect.SybaseAnywhereDialect Some dialects of different databases shaharyar.khan555@gmail.com
  • 26. <?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC  "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping>   <class name=“com .deltasoft.hibernate.Contact" table="CONTACT">    <id name="id" type="long" column="ID" >    <generator class="assigned"/>   </id>   <property name="firstName">    <column name="FIRSTNAME" />   </property>   <property name="lastName">   <column name="LASTNAME"/>   </property>   <property name="email">   <column name="EMAIL"/>   </property>  </class> </hibernate-mapping> 26 shaharyar.khan555@gmail.com
  • 27. 27 It is better to get these jar files like this  Go to http://sourceforge.net/projects/hibernate/files/  Click on Download hibernate-search-4.1.1.Final-dist.zip (31.0 MB)  Now a folder will be downloaded on your machine.  Extract the folder and in extracted folder you will see a folder “required” placed in “hibernate-search- 4.1.1.Final/dist/lib/required”  Copy all the jar files present in “required” folder into your classpath shaharyar.khan555@gmail.com
  • 28.  <hibernate-mapping> element The first or root element of hibernate mapping document is <hibernate-mapping> element. Between the <hibernate-mapping> tag class element(s) are present 28  <class> element The <Class> element maps the class object with corresponding entity in the database. It also tells what table in the database has to access and what column in that table it should use. Within one <hibernate-mapping> element, several <class> mappings are possible <id> element The <id> element in unique identifier to identify and object. In fact <id> element map with the primary key of the table. In our code : <id name="id" type="long" column="ID" > primary key maps to the ID field of the table CONTACT. The attributes of the id element are: name: The property name used by the persistent class. column: The column used to store the primary key value. type: The Java data type used. unsaved-value: This is the value used to determine if a class has been made persistent. If the value of the id attribute is null, then it means that this object has not been persisted. shaharyar.khan555@gmail.com
  • 29.  <generator> element The <generator> method is used to generate the primary key for the new record. Here is some of the commonly used generators :   Increment - This is used to generate primary keys of type long, short or int that are unique only. It should not be used in the clustered deployment environment.   Sequence - Hibernate can also use the sequences to generate the primary key. It can be used with DB2, PostgreSQL, Oracle, SAP DB databases.    Assigned - Assigned method is used when application code generates the primary key.  29  <property> element The property elements define standard Java attributes and their mapping into database schema. The property element supports the column child element to specify additional properties, such as the index name on a column or a specific column type shaharyar.khan555@gmail.com
  • 30.  Same like JSF and other frameworks of java , Hibernate also supports annotations  Now if we want to transfer our previous contact example into annotations then we havn’t need “contact.hbm.xml” so delete this if you want to introduce annotations in your code  Now our Contact.java would be like this 30 shaharyar.khan555@gmail.com
  • 31. 31 @Entity @Table(name="EMPLOYEE") public class Contact { @Id   @GeneratedValue   private long id; //Contact.java with annotations @Column(name="firstname“) private String firstName; @Column(name=“lastname“)   private String lastName; @Column(name=“email“)   private String email;    //getter and setters }      shaharyar.khan555@gmail.com
  • 32. 32  Now in FirstExample.java just change this line SessionFactory sessionFactory = new  Configuration().configure(). buildSessionFactory(); TO SessionFactory sessionFactory = new AnnotationConfiguration().configure() .buildSessionFactory(); And in hibernate.cfg.xml change this <mappingresource="net/viralpatel/hibernate/Employee.hbm.xml"/> TO <mapping class=“com.deltasoft.hibernate.Employee"/> shaharyar.khan555@gmail.com
  • 33. 33 We will discuss some these relations in our this session shaharyar.khan555@gmail.com
  • 34. 34  Lets take an example that  Employee has a one to one relation with EmployeeDetail  So, First we create a Employee class and then EmployeeDetail in which we map them by annotations shaharyar.khan555@gmail.com
  • 35.   @Entity @Table(name="EMPLOYEE") public class Employee {       @Id     @GeneratedValue     @Column(name="employee_id")     private Long employeeId;           @Column(name="firstname")     private String firstname;           @Column(name="lastname")     private String lastname;           @Column(name="birth_date")     private Date birthDate;           @Column(name="cell_phone")     private String cellphone;       @OneToOne(mappedBy="employee", cascade=CascadeType.ALL)     private EmployeeDetail employeeDetail;           public Employee() {               }           public Employee(String firstname, String lastname, Date birthdate, String phone) {         this.firstname = firstname;         this.lastname = lastname;         this.birthDate = birthdate;         this.cellphone = phone;               }       // Getter and Setter methods } 35 shaharyar.khan555@gmail.com
  • 36. <?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>         <!-- Database connection settings -->         <property name="connection.driver_class">com.mysql.jdbc.Driver</property>         <property name="connection.url">jdbc:mysql://localhost:3306/tutorial</property>         <property name="connection.username">root</property>         <property name="connection.password"></property>                   <property name="connection.pool_size">1</property>         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>         <property name="current_session_context_class">thread</property>         <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>         <property name="show_sql">true</property>         <property name="hbm2ddl.auto">validate</property>        <mapping class="net.viralpatel.hibernate.EmployeeDetail"/>     <mapping class="net.viralpatel.hibernate.Employee"/>                </session-factory> 36 shaharyar.khan555@gmail.com
  • 37. public class Main {        public static void main(String[] args) {           System.out.println("Hibernate One-To-One example (Annotation)");                   SessionFactory sf = = new AnnotationConfiguration().configure()                     .buildSessionFactory();         Session session = sf.openSession();         session.beginTransaction();           EmployeeDetail employeeDetail = new EmployeeDetail("10th Street", "LA", "San Francisco", "U.S.");                   Employee employee = new Employee(“Ali", “Asim", new Date(121212),                 "114-857-965");         employee.setEmployeeDetail(employeeDetail);         employeeDetail.setEmployee(employee);                             session.save(employee);       } 37 shaharyar.khan555@gmail.com
  • 39. @Entity @Table(name="EMPLOYEE") public class Employee {       @Id     @GeneratedValue     @Column(name="employee_id")     private Long employeeId;           @Column(name="firstname")     private String firstname;           @Column(name="lastname")     private String lastname;           @Column(name="birth_date")     private Date birthDate;           @Column(name="cell_phone")     private String cellphone;       @ManyToOne     @JoinColumn(name="department_id")     private Department department;           public Employee() {               }           public Employee(String firstname, String lastname, String phone) {         this.firstname = firstname;         this.lastname = lastname;         this.birthDate = new Date(System.currentTimeMillis());         this.cellphone = phone;     }     // Getter and Setter methods } 39 shaharyar.khan555@gmail.com
  • 40.  public class Main {       @SuppressWarnings("unchecked")     public static void main(String[] args) {           SessionFactory sf = = new AnnotationConfiguration().configure()                     .buildSessionFactory();         Session session = sf.openSession();         session.beginTransaction();           Department department = new Department();         department.setDepartmentName("Sales");         session.save(department);                   Employee emp1 = new Employee("Nina", "Mayers", "111");         Employee emp2 = new Employee("Tony", "Almeida", "222");           emp1.setDepartment(department);         emp2.setDepartment(department);                   session.save(emp1);         session.save(emp2);           session.getTransaction().commit();         session.close();     } } 40 shaharyar.khan555@gmail.com
  • 41. 41  Many Employees have many Meetings So  We will Map Employee class with meeting class shaharyar.khan555@gmail.com
  • 42. 42 @Entity @Table(name="EMPLOYEE") public class Employee {           @Id     @Column(name="EMPLOYEE_ID")     @GeneratedValue     private Long employeeId;           @Column(name="FIRSTNAME")     private String firstname;           @Column(name="LASTNAME")     private String lastname;           @ManyToMany(cascade = {CascadeType.ALL})     @JoinTable(name="EMPLOYEE_MEETING",                 joinColumns={@JoinColumn(name="EMPLOYEE_ID")},                 inverseJoinColumns={@JoinColumn(name="MEETING_ID")})     private Set<Meeting> meetings = new HashSet<Meeting>();           public Employee() {     }     public Employee(String firstname, String lastname) {         this.firstname = firstname;         this.lastname = lastname;     }         // Getter and Setter methods } shaharyar.khan555@gmail.com
  • 43. @Entity @Table(name="MEETING") public class Meeting {       @Id     @Column(name="MEETING_ID")     @GeneratedValue     private Long meetingId;       @Column(name="SUBJECT")     private String subject;           @Column(name="MEETING_DATE")     private Date meetingDate;           @ManyToMany(mappedBy="meetings")     private Set<Employee> employees = new HashSet<Employee>();           public Meeting(String subject) {         this.subject = subject;         this.meetingDate = new Date();     }           // Getter and Setter methods } 43 shaharyar.khan555@gmail.com
  • 44. 44 public class Main {        public static void main(String[] args) {            SessionFactory sf = new AnnotationConfiguration().configure()                     .buildSessionFactory();         Session session = sf.openSession();         session.beginTransaction();                      Meeting meeting1 = new Meeting("Quaterly Sales meeting");         Meeting meeting2 = new Meeting("Weekly Status meeting");                   Employee employee1 = new Employee("Sergey", "Brin");         Employee employee2 = new Employee("Larry", "Page");           employee1.getMeetings().add(meeting1);         employee1.getMeetings().add(meeting2);         employee2.getMeetings().add(meeting1);                   session.save(employee1);         session.save(employee2);                   session.getTransaction().commit();         session.close();     } } shaharyar.khan555@gmail.com
  • 45.  Hibernate Query Language or HQL for short is extremely powerful query language  HQL is much like SQL  and are case-insensitive, except for the names of the Java Classes and properties  Hibernate Query Language is used to execute queries against database  Hibernate automatically generates the sql query and execute it against underlying database if HQL is used in the application.  Hibernate Query Language uses Classes and properties instead of tables and columns. 45 shaharyar.khan555@gmail.com
  • 46. 46  Subqueries Subqueries are nothing but its a query within another query. Hibernate supports Subqueries if the underlying database supports it. shaharyar.khan555@gmail.com