Hibernate Interview Questions

Hibernate Introduction
  1. What is Hibernate ?
  2. Briefly explain Hibernate Architecture ?
  3. What is the use of ORM ?
  4. What is Java Persistence API(JPA) ?
  5. What is JDBC ?
  6. Why are you using hibernate when we have JDBC ?
  7. What are the advantages of hibernate ?
  8. Tell me drawbacks or disadvantages of hibernate ?
  9. Mention design patterns used in hibernate ?
  10. What is the general flow of Hibernate communication with RDBMS?
  11. The general flow of Hibernate communication with RDBMS is :
    Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files
    Create session factory from configuration object
    Get one session from this session factory
    Create HQL Query
    Execute query to get list containing Java objects
  12. How do you map Java Objects with Database tables?
  13. First we need to write Java domain objects (beans with setter and getter).
    Write hbm.xml, where we map java class to table and database columns to Java class variables.
    Example :
    
      
       
       
     
    
  14. What are the most common methods of Hibernate configuration?
  15. The most common methods of Hibernate configuration are:
    Programmatic configuration
    XML configuration (hibernate.cfg.xml)
  16. What is HQL ?
  17. What is hibernate configuration file ?
  18. What is hibernate mapping file ?
  19. What is the root node in hbm.xml file ?
  20. Some important tags or elements used in hbm.xml ?
  21. Following are the important tags of hibernate.cfg.xml:
  22. Mention some important annotations used in hiberante mapping ?
  23. What are the core interfaces of hibernate ? or What are the key components/elements/objects of hibernate ?
  24. What are the key components of hibernate Configuration Object ?
  25. Name some properties required to configure database in standalone situation ?
  26. Some important methods and their usage ?
  27. Session.beginTransaction method begins a unit of work and returns the associated Transaction object. Session.createCriteria creates a new Criteria instance, for the given entity class, or a superclass of an entity class. Session.createQuery creates a new instance of Query for the given HQL query string. Session.createSQLQuery creates a new instance of SQLQuery for the given SQL query string. Session.delete removes a persistent instance from the datastore. Session.get returns the persistent instance of the given named entity with the given identifier, or null if there is no such persistent instance. Session.refresh re-reads the state of the given instance from the underlying database. Session.save saves the state of the given instance from the underlying database. Session.update updates the state of the given instance from the underlying database. Session.saveOrUpdate either saves(Object) or updates(Object) the given instance.
  28. What is meant by persistent class in hibernate ?
  29. What are the best practices hibernate recommend for persistant classes ?
  30. What is meant by serializable ?
  31. What are the states of object in hibernate ?
  32. Whether Session Factory and Session are thread safe objects ?
  33. Difference between openSession and getCurrentSession ?
  34. Difference between session.save() and session.persist() methods ?
  35. Difference between get() and load() methods in hibernate ?
  36. Difference between update() and merge() methods in hibernate ?
  37. Difference between save() , saveOrUpdate() , persist() methods ?
  38. Mention the types of association mapping available in hibernate ?
  39. How do you implement associations or relationships in hibernate ?
  40. Mention the inheritance models in hibernate ?
  41. What is meant by immutable class ? How can you make a class immutable in hibernate ?
  42. What is meant by automatic dirty check in hibernate ?
  43. Which association's are possible with Collections interface or with Collection classes ?
  44. What is hibernate Proxy ?
  45. What is meant by lazy loading in hibernate ?
  46. What is meant by hibernate caching ?
  47. What is meant by first level cache ?
  48. What is meant by second level cache ?
  49. What is meant by Query cache in hiberante ?
  50. Mention collection types in hibernate ?
  51. What is bag collection in hibernate ?
  52. How to fetch ordered collection from database in hibernate ?
  53. How can Hibernate be configured to access an instance variable directly and not through a setter method ?
  54. By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

  55. Difference between ordered collection and sorted collection ? Which one is better in hibernate ?
  56. Tell me about joins in hibernate ?
  57. HQL provides four ways of expressing (inner and outer) joins:-
    An implicit association join
    An ordinary join in the FROM clause
    A fetch join in the FROM clause.
    A theta-style join in the WHERE clause.
    
  58. What is native sql query ? Can we execute them in hibernate ?
  59. What is the advantage of native sql query support in hibernate ?
  60. What is Named SQL Query ?
  61. What are the Mandatory things for a java object to become Hibernate Entity object ?
  62. What is Entity class ?
  63. What happens if we make our Entity class as final in hibenate ?
  64. Define cascade and inverse option in one-many mapping?
  65. cascade - enable operations to cascade to child entities.
    cascade="all|none|save-update|delete|all-delete-orphan"
    
    inverse - mark this collection as the "inverse" end of a bidirectional association.
    inverse="true|false" 
    Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?
  66. Explain about log4j logging in hibernate ?
  67. How to log SQL queries into log files in hibernate ?
  68. What is transaction Management ? How it works in hibernate ?
  69. A org.hibernate.Session is designed to represent a single unit of work (a single atmoic piece of work to be performed.
    Sample code of handling transaction from hibernate session.
    Session session = HibernateUtil.getSessionFactory().getCurrentSession();
            session.beginTransaction();
            Event theEvent = new Event();
            theEvent.setTitle(title);
            theEvent.setDate(theDate);
            session.save(theEvent);
            session.getTransaction().commit();
  70. What is Cascading ? Mention different types of Cascading ?
  71. How to configure application server JNDI DataSource with Hibernate Framework ?
  72. How to integrate Spring and Hibernate frameworks ?
  73. What is hibernate Validator Framework ?
  74. What are concurrency strategies ?
  75. What is N+1 Select problem in hibernate ? Mention some strategies to solve it ?
  76. How to implement Optimistic locking in Database?
  77. You can implement optimistic locks in your DB table in this way (This is how optimistic locking is done in Hibernate):
    - Add integer "version" column to your table.
    - Increase value of this column with each update of corresponding row.
    - To obtain lock, just read "version" value of row.
    - Add "version = obtained_version" condition to where clause of your update statement.
    - Verify number of affected rows after update. If no rows were affected - someone has already modified your entry.
    Your update should look like
       UPDATE mytable SET name = 'Andy', version = 3 WHERE id = 1 and version = 2;
    
  78. What are Callback interfaces? Callback interfaces allow the application to receive a notification when something interesting happens to an object—for example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.
  79. What is transactional write-behind? Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.
  80. What do you mean by fetching strategy ? A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.
  81. What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
  82. Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.
  83. How do you define sequence generated primary key in hibernate?
  84. Using  tag.
    Example:-
     
        
         SEQUENCE_NAME
       
    
  85. Define HibernateTemplate?
  86. org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.
  87. What are the benefits does HibernateTemplate provide?
  88. The benefits of HibernateTemplate are : HibernateTemplate, a Spring Template class simplifies interactions with Hibernate Session. Common functions are simplified to single method calls. Sessions are automatically closed. Exceptions are automatically caught and converted to runtime exceptions.
  89. How do you switch between relational databases without code changes?
  90. Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
  91. If you want to see the Hibernate generated SQL statements on console, what should we do?
  92. In Hibernate configuration file set as follows: true
  93. What are derived properties?
  94. The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.
  95. What is component mapping in Hibernate?
  96. A component is an object saved as a value, not as a reference. A component can be saved directly without needing to declare interfaces or identifier properties. Required to define an empty constructor. Shared references not supported.
  97. What is Hibernate Criteria API ?
  98. Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set. Example : List employees = session.createCriteria(Employee.class) .add(Restrictions.like("name", "a%") ) .add(Restrictions.like("address", "Boston")) .addOrder(Order.asc("name") ) .list();
  99. How do you invoke Stored Procedures?
  100. 
     
              
    
              
       
        { ? = call selectAllEmployees() }
     
    


Disadvantages of Hibernate

Advantages of Hibernate
  • Slower than JDBC: Hibernate is slower than pure JDBC as it generates lot of SQL statements in runtime.

  • Lots of API to learn: A lot of effort is required to learn Hibernate. So, not very easy to learn hibernate easily.

  • Not suitable for Batch processing: It advisable to use pure JDBC for batch processing ,which takes less time for processing than hibernate.

  • Debugging: Sometimes debugging and performance tuning becomes difficult.

  • Not suitable for Small projects : For small projects having few tables it is useless to work with hibernate.

  • Does not allow multiple inserts : Hibernate does not allow some type of queries which are supported by JDBC.

    For example: It does not allow to insert multiple objects (persistent data) to same table using single query.

    Developer has to write separate query to insert each object into database.

  • Generates complex quires with many joins : For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.



Advantages of Hibernate

Advantages of Hibernate
  • Hibernate is an ORM (object relational mapping) tool which is better than JDBC.

  • Hibernate framework is opensource under the LGPL license and lightweight because it uses POJO classes for data transfer between application and database.

  • Hibernate is Easy to maintain and it will increases productivity.

  • Hibernate has versioning and time stamp feature with this we can know how many number of times data is modified.

  • Hibernate has its own query language, i.e hibernate query language which is database independent so that it supports various databases.

  • Hibernate supports collections(List,Set,Map).

  • Hibernate supports inheritance, i.e if we save the derived class object, then its base class object will also be stored into the database which indicates inheritance.

  • Hibernate supports polymorphism

  • Hibernate supports associations by managing the data stored across multiple tables by applying relations.

  • Hibernate has an exception translator , which converts checked exceptions of JDBC in to unchecked exceptions of hibernate. So all exceptions in hibernate are unchecked exceptions , so no need to handle exceptions explicitly by writing try, catch blocks or no need to use throws keyword next to method.

  • Hibernate supports relationships like One-To-Many,One-To-One, Many-To-Many-to-Many, Many-To-One.

  • Hibernate supports Lazy loading , annotations along with XML.
  • Hibernate supports caching mechanism so that the number of interactions between an application and the database will be reduced, by using this caching technique an application performance will be increased automatically.

  • Hibernate has capability to generate primary keys automatically while we are storing the records into database.

  • Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods provided by that API.

  • Pagination in hibernate is quite simple.



Hibernate Architecture

Hibernate Architecture

Hibernate application has four layers.

  • Java application layer.
  • Hibernate framework layer
  • Backhand api layer
  • Database layer
High level view of the Hibernate Application Architecture:
Detailed view of the Hibernate Application Architecture with important core classes:

About JDBC , JTA , JNDI

Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and Directory Interface (JNDI).

JDBC provides a basic level of abstraction of functionality common to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate.

JNDI and JTA allow Hibernate to be integrated with J2EE application servers.

Hibernate Objects:

The Hibernate architecture includes many objects as shown in above detailed view.

  • Configuration
  • SessionFactory
  • Session
  • TransactionFactory
  • Query
  • Criteria
Objects Functionality :
  • Configuration Object:

    It is the first Hibernate object you create in any Hibernate application and usually created only once during application initialization.

    It represents a configuration or properties file required by the Hibernate. The Configuration object provides two key components:

    1. Database Connection: This is handled through one or more configuration files supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
    2. Class Mapping Setup : This component creates the connection between the Java classes and database tables.

  • SessionFactory:

    Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the application using the supplied configuration file and allows for a Session object to be instantiated. The SessionFactory is a thread safe object and used by all the threads of an application.

    The SessionFactory is heavyweight object so usually it is created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file. So if you are using multiple databases then you would have to create multiple SessionFactory objects.

    The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of Session.

  • Session:

    The session object provides an interface between the application and data stored in the database.

    It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria.

    It is lightweight and designed to be instantiated each time an interaction is needed with the database. Persistent objects are saved and retrieved through a Session object.

    This object should not be kept open for a long time because they are not usually thread safe.

  • Transaction:

    The transaction object specifies the atomic unit of work that deals with with the database and most of the RDBMS supports transaction functionality. The org.hibernate.Transaction interface provides methods for transaction management.

    Transactions in Hibernate are handled by an underlying transaction manager and transaction (from JDBC or JTA).

    This is an optional object and Hibernate applications may choose not to use this interface, instead managing transactions in their own application code.

  • TransactionFactory:

    It is a factory of Transaction objects. It is optional.

  • Query Object:

    Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database and create objects. A Query instance is used to bind query parameters, limit the number of results returned by the query, and finally to execute the query.

  • Criteria Object:

    Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

  • ConnectionProvider:

    It is a factory of JDBC connections. It abstracts the application from DriverManager or DataSource. It is optional.



Hibernate Introduction

Hibernate Introduction

What is Hibernate ?

1) Hibernate framework is an Object-relational mapping (ORM) tool which interacts with the database tables.

2) It is open source , light weight , ORM (Object Relational Mapping) tool given by Gavin King.

3) It is called as ORM tool because it maps application domain model objects (POJO class objects) to the relational database tables with the help of a mapping file(xml).

4) It is purely for persistance and simplifies CRUD(Creating , Reading , Updating , Deleting) operations. It internally uses JDBC API to interact with database.

5) It is suitable for all types of applications (Desktop , mobile , stand alone apps) and can run with or with our server.





ORACLE ATG INSTALLATION AND CONFIGURATION

ATG INSTALLATION AND CONFIGURATION

      Here in this page we will discuss how to set up Oracle ATG in our local system and configure it.

Steps to be Followed :

1.    First set JAVA_HOME and PATH  Environment variables.
       Where  JAVA_HOME points to your JDK directory  and PATH point to your
        JDK / bin directory.

      Note : Install JDK in any of your root directory like C drive not in program files
      and your directories should be like below.

       JAVA_HOME="C:\Java\jdk1.8.0_xx".
       PATH
+="C:\Java\jdk1.8.0_xx\bin".      
       For PATH variable add the JDK/bin directory by using ";" (semicolon);
       Where xx denotes your java version update number.

       Set the above Environment variables in your system.

       For in detail how to install JAVA and environment variables in your system .
       Please go to : How to Install Java and Environment variables.

2.   Install Weblogic in your system and start the Weblogic server.

     On Linux, enter:  ./startWebLogic.sh

     On Windows, start : startWebLogic.cmd file

     After weblogic has started you will get the following message.


      After that go to http://hostname:7001/console to start the WebLogic Server
      Administration Console and enter Weblogic username and passoword to Log In.

      For in detail how to install Weblogic in your system .
      Please go to : WEBLOGIC INSTALLATION










WEBLOGIC INSTALLATION

Steps to be followed for installing weblogic in windows :

1.  First download the weblogic from the link Download Oracle Weblogic by
     accepting the terms and conditions.
2. Create a folder Oracle in C drive or D drive eg : [C:\Oracle] and after that
    create an environment variable ORACLE_HOME as variable name and
    value will be C:\Oracle in my case.
3. After that check whether environment variable set to the directory or not.
    By using following command in command prompt.
 => echo %ORACLE_HOME%
   Then it should print the as below. If not recheck and restart your system.


4. Then extract the downloaded weblogic zip folder and copy the
   fmw_12.2.1.2.0_wls_quick jar in your C:\Oracle folder.
5.   Open command prompt and go to C:\Oracle by typing below command.
  => cd C:\Oracle

6.   If java is not installed properly you will not able to proceed further steps.
      If you didn't installed Java earlier go to : Java Installation Steps  and
      install  Java first.

JAVA INSTALLATION ON WINDOWS



JAVA INSTALLATION :


Note:  Before installing Java in your machine , Uninstall all older or other versions of Java and check whether your required Java version is already Installed bcoz sometimes our required version might be already installed .


Steps to Install Java (JDK) in your machine :

1. First of all check whether java already installed or not installed.

To check which version of java installed in your machine.

Go to command prompt and type the following command :

// For  Displaying the JRE version
cmd> java -version
java version "1.8.0_xx"
Java(TM) SE Runtime Environment (build 1.8.0_xx-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.5-b02, mixed mode)
 
//For  Displaying the JDK version
cmd> javac -version
javac 1.8.0_xx




Here as per above screenshot installed version is 1.8.0_25 . 
 If java is not properly installed on your system then you will get a message as below screenshot.
 'java' is not reconnized as an internal or external command.


So , after checking java version then go for uninstalling the installed java and install required version of your java version.

Uninstall java from controlpanel =>  uninstall or change a program => uninstall your old java.

2.  Go to http://www.oracle.com/technetwork/java/javase/downloads/index-jsp-138363.html  .


    As  per your system configuration whether it is 32 bit or 64 bit download the related JDK.

⇒ "Java SE 8u{xx}", where {xx} is the latest update number ⇒ Click the "JDK Download" button after accepting the "Accept License agreement" radio button.

Both JDK and JRE will be installed in the below locations:
JDK in : C:\Program Files\Java\jdk1.8.0_25

JRE in : C:\Program Files\Java\jre1.8.0_31


3.  After installation of JDK and JRE , we have to set or edit the PATH environment variable in
our system.
WHAT IS THE NEED OF PATH VARIABLE ?

Windows OS searches the current directory and the directories listed in the PATH environment
variable for executable programs.
JDK's programs (such as Java compiler javac.exe and Java runtime java.exe) reside in directory"C:\Program Files\Java\jdk1.8.0_xx\bin" .

So we have to set PATH variable in our system which points to the directory  "C:\Program Files\Java\jdk1.8.0_xx\bin".

In general we call JDK installed directory as "JAVA_HOME".

JAVA_HOME="C:\Program Files\Java\jdk1.8.0_xx".

PATH="C:\Program Files\Java\jdk1.8.0_xx\bin".

How to Set or Edit PATH Variable in our system ?

To edit the PATH environment variable in Windows XP/Vista/7/8/10:
  1. Launch "Control Panel" ⇒ "System" ⇒ Click "Advanced system settings".
  2. Switch to "Advanced" tab ⇒ "Environment Variables".
  3. Under "System Variables", scroll down to select "Path" ⇒ "Edit...".

    For all Window versions except 10 : 

      1.  In "Variable value" field, insert  "c:\Program Files\Java\jdk1.8.0_xx\bin" (Replace xx with your installation upgrade number) 
      2.  IN FRONT of all the existing directories, followed by a semi-colon (;) which           separates the JDK's binary directory from the rest of the existing directories.

      Note: DO NOT DELETE any existing entries; otherwise, some existing applications may not run.

    For Windows 10: 

    1. You see a table listing the existing PATH entries.

    Click "New" ⇒ Enter the JDK's binary directory "c:\Program Files\Java\jdk1.8.0_xx\bin" (Replace xx with your installation's upgrade number!!!) 
    ⇒ Select "Move Up" to move it all the way to the top.

    2. In "Variable value" field, INSERT "c:\Program Files\Java\jdk1.8.0_xx\bin" (Replace xx with your installation upgrade number!!!) 

    3. IN FRONT of all the existing directories, followed by a semi-colon (;) which separates the JDK's binary directory from the rest of the existing directories. 


4.    After setting or editing the PATH envirounment variable . Check whether it is set exactly to the location "C:\Program Files\Java\jdk1.8.0_xx\bin". By typing the following command in command Prompt.

cmd > path



    Note:  Observe in the path variable they are many other application locations . This is the reason while editing PATH variable should be careful with out deleting existing applications.


=> Follow step 1 and check whether JDK and JRE installed exactly or not. 

=> Sometimes even if you installed Properly it may not reflect in cmd .
      In such scenarios restart your system.

=> For checking Environment variabes set properly or not . Use the
      following commands and it should show it's corresponding path you set.

     =>echo %JAVA_HOME%  which should show JDK directory.
     =>echo %ORACLE_HOME% which should show appserver home directory.
     =>echo %PATH%  which show JDK/bin directory along with other applications
          installed.

150 ATG MCQ'S

ATG MULTIPLE CHOICE QUESTIONS :

1. ATG MCQ'S  1-10

2. ATG MCQ'S  11-20

3. ATG MCQ'S  21-30

4. ATG MCQ'S  31-40

5. ATG MCQ'S  41-50

6. ATG MCQ'S  51-60

7. ATG MCQ'S  61-70

8. ATG MCQ'S  71-80

9. ATG MCQ'S  81-90

10. ATG MCQ'S  91-100

11. ATG MCQ'S  101-110

12. ATG MCQ'S  111-120

13. ATG MCQ'S  121-130

14. ATG MCQ'S  131-140

15. ATG MCQ'S  141-150

ATG INTERVIEW QUESTIONS :   ATG INTERVIEW Q&A's

Featured Post

H1B Visa Stamping at US Consulate

  H1B Visa Stamping at US Consulate If you are outside of the US, you need to apply for US Visa at a US Consulate or a US Embassy and get H1...