Tuesday, May 1, 2012

HIBERNATE FRAMEWORK

  1. What is Hibernate ?
  2. What is HQL?
  3. Explain the advantages of Hibernate?
  4. Why is ORM preferred over JDBC?
  5. Mention the Key components of Hibernate?
  6. Explain the Session in Hibernate?
  7. Explain the Transaction object in Hibernate?
  8. Explain the Criteria object in Hibernate?
  9. Explain the Query object in Hibernate?
  10. Mention some of the databases that Hibernate supports?
  11. What is a One-to-One association in Hibernate?
  12. What is One-to-Many association in Hibernate?
  13. What is a Many-to-One association in Hibernate?
  14. What is Many-to-Many association in Hibernate?
  15. What is Hibernate caching?
  16. What is first level cache in Hibernate?
  17. What is second level cache in Hibernate?
  18. What is Query level cache in Hibernate?
  19. Explain Hibernate configuration file and Hibernate mapping file?
  20. What are concurrency strategies?
  21. What is Lazy loading?
  22. Explain the persistent classes in Hibernate?
  23. Explain some of the elements of hbm.xml?
  24. Describe the method used to create an HQL Query and SQL Query?
  25. Explain the important benefits of Hibernate framework?
  26. Describe the important interfaces of Hibernate framework?
  27. What is difference between save and persist in hibernate?
  28. Explain what is a dialect?
  29. Which annotation is used to declare a class as a hibernate bean?
  30. What inheritance mapping strategies are available in Hibernate?

@1 Question

What is Hibernate ?


  • Hibernate is a Open source , non invasive ,light weight Java ORM(Object-relational mapping) framework .
  • Given by SoftTree (Redhat) to develop object based on DATABASE software independent O-R mapping persistence logic's in all kind of java applications.    
  • It is written in Java.
  • Along with hibernate installation we get its source code in <Hibernate_Home> project\hibernate-core folder.
  • Hibernate is light weight and comes in small size.
  • To execute hibernate we don't need heavy weight container like tomcat and jboss etc... just having JDK(Java Development Kit) and hibernate libraries we can execute hibernate code.
  • Hibernate persistence logic is interchangeable with any java technologies/code java framework based applications.
  • EJB Entity bean component allows as developing  object based O-R mapping ,but these components are heavy weight components. 
  • Hibernate provides the data query and retrieval facilities.
  • It is one of the most widely used ORM tools for the Java applications.
  • Hibernate is highly considered to be used in the enterprise applications for database operations.

#2 Question

What is HQL?

  • HQL is the acronym of Hibernate Query Language.It considers the java objects in a similar way as that of the SQL.
  • It is an Object-Oriented Query Language and is independent of the database.

#3 Question

Explain the advantages of Hibernate?

Some of the advantages of Hibernate are:
  • It provides Simple Querying of data.
  • An application server is not required to operate.
  • The complex associations of objects in the database can be manipulated.
  • Database access is minimized with smart fetching strategies.
  • It manages the mapping of Java classes to database tables without writing any code.
  • Properties of XML file is changed in case of any required change in the database.

#4 Question

Why is ORM preferred over JDBC?

  • It allows business code access the objects rather than Database tables.
  • It hides the details of SQL queries from OO logic.
  • It is based on JDBC “under hood”.
  • Dealing with database implementation is not required.
  • Entities are based on business concepts rather than database structures.
  • It generates the automatic key and Transaction management.
  • Application development is faster.

#5 Question

Mention the Key components of Hibernate?

The Key components of Hibernate are:
  • Session: It is used to get a physical network with a database.
  • Transaction: It represents the unit of work with a database.
  • Query: It uses SQL and HQL string to retrieve the data from the database and create objects.
  • Criteria: It is used create and execute object-oriented queries and retrieve the objects.
  • Configuration: It represents the properties of files required by Hibernate
  • Session Factory: It configures hibernate for the application using the provided configuration file and instantiates the session object.

#6 Question

Explain the Session in Hibernate?

  • It is used to get a physical connection with a database. A session object is designed to instantiate each time an interaction is required with the database, whereas the persistent objects are retrieved using a session object.
  • The session objects are not thread-safe and must be created and destroyed as per the requirement.

#7 Question

Explain the Transaction object in Hibernate?

It represents a unit of work with the database and most of the RDBMS (Relational Database Management System) supports transaction functionality.
In Hibernate, transactions are managed by an underlying transaction manager and transaction from JDBC or JTA.
It is an optional object and the Hibernate Application do not use this interface, instead, they handle the transactions in their code.

#8 Question

Explain the Criteria object in Hibernate?

Criteria objects are used to create and execute object-oriented Queries to retrieve the objects.

#9 Question

Explain the Query object in Hibernate?

These objects use SQL and HQL string to retrieve data from the database and create objects.
An instance of Query is used to bind query parameters, restrict the number of results returned by the query and finally to execute the query.

#10 Question

Mention some of the databases that Hibernate supports?

Hibernate supports all the major RDMS.Following are the list of database engines supported by Hibernate:
  • HSQL Database Engine
  • DB2/NT
  • Oracle
  • Microsoft SQL Server Database
  • Sybase SQL Server
  • Informix Dynamic Server
  • MySQL
  • PostgreSQL
  • FrontBase

#11 Question

What is a One-to-One association in Hibernate?

It is similar to the many-to-one association and the difference lies in the column that will be set as a unique one.The many-to-one element is used to define one-to-one association.
To the defined variable a name attribute is set in the parent class and the column attribute is used to set column name in the parent table, which is unique so that only one object gets associated with another.

#12 Question

What is One-to-Many association in Hibernate?

In this association, one object can be associated with multiple objects.
The One-to-Many mapping is implemented using a Set Java collection that does not have any redundant element.
A One-to-Many element of the set element indicates the relation of one object to multiple objects. 

#12 Question

What is a Many-to-One association in Hibernate?

This association is the common type of association where one object can be associated with multiple objects.
And Many-to-one element defines the Many-to-One association.To the defined variable, a name attribute is set in the parent class and column attribute sets the column name in the parent table.

#13 Question

What is Many-to-Many association in Hibernate?

The Many-to-Many element indicates the relation between one object to many other objects and column attribute is used to link intermediate columns. A Many-to-Many mapping is implemented using a Set Java collection that does not have any redundant element.

#14 Question

What is Hibernate caching?

Hibernate caches Query data and makes the application run faster.
If used correctly, the hibernate cache can be very useful in achieving the faster application running performance.
The main idea lying behind the cache is reducing the number of database queries, which results in reduced throughput time of the application.

#15 Question

What is first level cache in Hibernate?
It is session cache and mandatory cache.It is from first level cache through which all the requests must pass.
The session object stores an object under its control before committing it to the database.

#16 Question

What is second level cache in Hibernate?

It is an optional cache. And, always the first level cache will be consulted before any attempt is performed to locate an object in the second level cache. This cache can be configured on a pre-collection and per-class basis and it is mainly responsible for caching objects across the sessions.

#17 Question


What is Query level cache in Hibernate?

In hibernate, a cache query can be implemented that results in sets and integrates closely with the second level cache.It is an optional feature and it requires two additional cache regions that can hold the cached query results and also the timestamps whenever a table is updated. This is useful only for the queries that run frequently holding the same parameters. 

#18 Question


Explain Hibernate configuration file and Hibernate mapping file?

Hibernate configuration file:
It contains database specific configurations and is used to initialize SessionFactory.
It provides database credentials or JNDI resource information in the hibernate configuration XML file.
Dialect information is another important part of the hibernate configuration file.
Hibernate Mapping file:
It is used to define the database table column mappings and entity bean fields.
We use JPA annotations for mappings, but when we are using the third party classes sometimes XML mapping files becomes handy and we cannot use annotations.

#20 Question

What are concurrency strategies?

The concurrency strategies are the mediators who are responsible for storing items and retrieving them from the cache.In case of enabling a second level cache, the developer must decide for each persistent class and collection, and also which cache concurrency, has to be implemented.
Following are the concurrency strategies that can be implemented by the developer:
  • Transactional: This strategy is used mostly to read data where the prevention of stale data is critical in concurrent transactions, in the unique case of an update.
  • Read- Only: This strategy is compatible with the data that can’t be modified. We can use it for reference data only.
  • Read-Write: It is similar to transactional strategy. where we read mostly data and prevention of stale data is critical.
  • Non-strict-Read-Write: This strategy assures no guarantee of consistency between the database and cache. We can use this strategy only if the data can be modified and a small likelihood of stale data is not the critical concern.

#21 Question

What is Lazy loading?

It is a technique in where the objects are loaded on the requirement basis.
Since the Hibernate 3 version, the lazy loading is by default enabled so that the child objects are not loaded while the parent is loaded.

#22 Question

Explain the persistent classes in Hibernate?

In hibernate, the Java classes whose instances and objects are stored in database classes are called persistent classes.

#23 Question

Explain some of the elements of hbm.xml?

  • It is used to define specific mappings from Java classes to database tables.
  • It is used to define the mapping of unique ID attribute in class to the primary key of the database table.
  • It is used to generate the primary key values automatically.
  • It is used to map a Java class property to a column in the database table.
  • It is used to map a java.util.set, java.util.Sortedset property in hibernate.
  • It is used to map a java.util.List property in hibernate.
  • It is used to map a java.util.Collection property in hibernate.
  • It is used to map a java.util.Map property in hibernate.

#24 Question

Describe the method used to create an HQL Query and SQL Query?

Session.createQuery is used to create a new instance of a query for the HQL query string.
Session.createSQLQuery is used to create a new instance of a query for the SQL query string.

#25 Question

Explain the important benefits of Hibernate framework?

Few important benefits of Hibernate framework are:
  • Hibernates allows us to focus on business logic, eliminating all the boiler-plate code that comes with JDBC and handles the resources.
  • Code implementation becomes independent as Hibernate framework provides the support for XML and also to the JPA annotations.
  • HQL is powerful Query Language which is similar to SQL, and HQL understands the concepts of polymorphism, inheritance, and association, which makes it fully object-oriented.
  • Better performance can be achieved by Hibernate cache.
  • It supports Lazy initialization with the use of proxy objects and when required performs actual database queries.
  • We can execute native SQL queries using hibernate for vendor specific feature.
On the whole, hibernate makes it a better choice in the current market for ORM tool, as it contains all the features that you will require in an ORM tool.

#26 Question

Describe the important interfaces of Hibernate framework?

Important interfaces of Hibernate framework are:
  • SessionFactory (org.hibernate.SessionFactory)
    It is an immutable thread safe cache of compiled mappings for a single database.
    We are supposed to initialize SessionFactory once and then we are allowed to cache and reuse it.
    The SessionFactory instance is used to return the session objects for database operations.
  • Session (org.hibernate.Session)
    It is a single threaded and short-lived object, which represents a conversation between the persistent store and the application.
    The session should be opened only when it is required and should be closed as soon as the user is done.
    The session object is the interface between hibernate framework and Java application code and it provides methods for the CRUD operations.
  • Transaction (org.hibernate.transaction)
    It is a single threaded and short-lived object used by the application, which specifies atomic units of work.
    The application is abstracted from the underlying JDBC or JTA transaction.

#27 Question

What is difference between save and persist in hibernate?

Difference between save and persist in Hibernate
DifferenceSavePersist
Return TypeReturns Serializable objectReturns Void

#27 Question

Explain what is a dialect?

  • The dialect specifies the type of database used in hibernate so that hibernate generate appropriate type of SQL statements. For connecting any hibernate application with the database, it is required to provide the configuration of SQL dialect.
  • <property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>  
  • List of SQL Dialects

    There are many Dialects classes defined for RDBMS in the org.hibernate.dialect package. They are as follows:


    RDBMSDialect
    Oracle (any version)org.hibernate.dialect.OracleDialect
    Oracle9iorg.hibernate.dialect.Oracle9iDialect
    Oracle10gorg.hibernate.dialect.Oracle10gDialect
    MySQLorg.hibernate.dialect.MySQLDialect
    MySQL with InnoDBorg.hibernate.dialect.MySQLInnoDBDialect
    MySQL with MyISAMorg.hibernate.dialect.MySQLMyISAMDialect
    DB2org.hibernate.dialect.DB2Dialect
    DB2 AS/400org.hibernate.dialect.DB2400Dialect
    DB2 OS390org.hibernate.dialect.DB2390Dialect
    Microsoft SQL Serverorg.hibernate.dialect.SQLServerDialect
    Sybaseorg.hibernate.dialect.SybaseDialect
    Sybase Anywhereorg.hibernate.dialect.SybaseAnywhereDialect
    PostgreSQLorg.hibernate.dialect.PostgreSQLDialect
    SAP DBorg.hibernate.dialect.SAPDBDialect
    Informixorg.hibernate.dialect.InformixDialect
    HypersonicSQLorg.hibernate.dialect.HSQLDialect
    Ingresorg.hibernate.dialect.IngresDialect
    Progressorg.hibernate.dialect.ProgressDialect
    Mckoi SQLorg.hibernate.dialect.MckoiDialect
    Interbaseorg.hibernate.dialect.InterbaseDialect
    Pointbaseorg.hibernate.dialect.PointbaseDialect
    FrontBaseorg.hibernate.dialect.FrontbaseDialect
    Firebirdorg.hibernate.dialect.FirebirdDialect

#29 Question

Which annotation is used to declare a class as a hibernate bean?

@Entity annotation is used to declare a class as an entity.
Example
@Entity
@Table(name="posts")
public class Post{
String title;
String description;
}

 #30 Question

What inheritance mapping strategies are available in Hibernate?

Hibernate have 3 ways of inheritance mapping, They are
  • Table per hierarchy
  • Table per concrete class
  • Table per subclass

#31 Question

What is transient state in hibernate ?


Transient, Persistent and Detached Objects in Hibernate

1. Transient State:

 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:
UserDetail user = new UserDetail();
user.setUserName("Dinesh Rajput");
// user is in a transient state

2. Persistent State:

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(user);
// user is now in a persistent state

3. Detached State:

Now, if we close the Hibernate Session, the persistent instance will become a detached instance: it isn’t attached to a Session anymore (but can still be modified and reattached to a new Session later though).
session.close();
//user in detached state

Difference between Transient and Detached States:

Transient objects do not have association with the databases and session objects. They are simple objects and not persisted to the database. Once the last reference is lost, that means the object itself is lost. And of course , garbage collected. The commits and rollbacks will have no effects on these objects. They can become into persistent objects through the save method calls of Session object.
The detached object have corresponding entries in the database. These are persistent and not connected to the Session object. These objects have the synchronized data with the database when the session was closed. Since then, the change may be done in the database which makes this object stale. The detached object can be reattached after certain time to another object in order to become persistent again.
Lets see in the following example to save or update the user data…
package com.sdnext.hibernate.tutorial;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

import com.sdnext.hibernate.tutorial.dto.UserDetails;

public class HibernateTestDemo {
 /**
  * @param args
  */
 public static void main(String[] args)
 {
  UserDetails userDetails = new UserDetails();
                userDetails.setUserName("Dinesh Rajput");
                userDetails.setAddress("Noida City");
  //Here 'userDetails' is TRANSIENT object
 
                SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
  Session session = sessionFactory.openSession();
  session.beginTransaction();
 
   session.save(userDetails);
  //Here 'userDetails' is PERSISTENT object
   userDetails.setUserName("User Updated after session close");

                session.getTransaction().commit();
  session.close();
  //Here 'userDetails' is DETACHED object
 }
}

Transient, Persistent and Detached state

#32 Question

How to write composite key mapping for hibernate?


In the context of relational databases, a composite key is a combination of two or more columns in a table that can be used to make the uniqueness of a table row. In this tutorials, we are going to implement how to define a hibernate composite key, and how to map the database composite primary keys in a hibernate mapping. Here is the example for Hibernate composite key:

Hibernate Composite Key Mapping :

Lets create a database table with composite primary key.
·       CREATE TABLE `student` (
·       `studentid` int(11) NOT NULL AUTO_INCREMENT,
·       `courceid` int(11) NOT NULL,
·       `studentname` varchar(50) DEFAULT NULL,
·       `studentAddress` varchar(50) DEFAULT NULL,
·       PRIMARY KEY (`studentid`,`courceid`)
·       ) ENGINE=InnoDB AUTO_INCREMENT=1

Maven dependency
<dependencies>
<!-- Hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.3.0.Final</version>
</dependency>
<!-- MySQL Driver -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.0.5</version>
</dependency>
</dependencies>

HibernateUtility : HibernateUitl.java
package com.stickiton.util;
import org.hibernate.SessionFactory;

import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import org.hibernate.cfg.Configuration;

 

public class HibernateUtil {

    private HibernateUtil() {

 

    }

 
    private static SessionFactory sessionFactory;
 
    public static synchronized SessionFactory getInstnce() {
 
        if (sessionFactory == null) {
            Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
                    .applySettings(configuration.getProperties());
            sessionFactory = configuration.buildSessionFactory(builder.build());
        }
        return sessionFactory;
 
    }

}



Hibernate POJO: Student.java

package com.stickiton.beans;

import java.io.Serializable;

 

public class Student implements Serializable {

 

    private static final long serialVersionUID = 1L;

    private int studentId;

    private String studentName;

    private String studentAddress;

    private int courceId;
 
    public int getStudentId() {
        return studentId;
    }
    public void setStudentId(int studentId) {
        this.studentId = studentId;
    }
    public String getStudentName() {
        return studentName;
    }
    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }
    public String getStudentAddress() {
        return studentAddress;
    }
    public void setStudentAddress(String studentAddress) {
        this.studentAddress = studentAddress;
    }
    public int getCourceId() {
        return courceId;
    }
    public void setCourceId(int courceId) {
        this.courceId = courceId;
    }
 

}

·       To represent the composite key in hibernate, the pojo class should implement the Serializable interface. Otherwise hibernate will throw org.hibernate.MappingException like "Composite-id class must implement Serializable"



Hibernate Mapping File : student.hbm.xml
 <?xml version="1.0" encoding="UTF-8"?>
 <!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.stickiton.beans.Student" table="student">

 <composite-id>

 <key-property name="studentId" column="studentid" />

 <key-property name="courceId" column="courceid" />

 </composite-id>

 <property name="studentName" />

 <property name="studentAddress" />

 </class>
 </hibernate-mapping>

·       To represent the composite keys, hibernate provides <key-property> tag under the <composite-id> tag.
·       We can represent each primary key with <key-property> tag, so that all primary keys will be binded with the <composite-id> tag.

Lets Run the Application : Main.java
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import com.stickiton.beans.Student;
import com.stickiton.util.HibernateUtil;

public class Main {
    public static void main(String args[]) {
        SessionFactory sessionFactory = HibernateUtil.getInstnce();
        Session session = sessionFactory.openSession();
        Student student = new Student();
        student.setStudentId(103);
        student.setStudentAddress("Hyderabad");
        student.setStudentName("Johny");
        student.setCourceId(201);
        Transaction tx = session.beginTransaction();
        session.save(student);
        tx.commit();
        session.close();
    }
}
Output:
·       Hibernate: insert into student (studentName, studentAddress, studentid, courceid) values (?, ?, ?, ?)

Hibernate composite key table


No comments:

Post a Comment