Saturday, July 12, 2014

Hibernate Basics

Hibernate Life Cycle:
Hibernate defines and supports the following objects states:
  • Transient- an object is transient if t has been instantiated using the new operator, and it is not associated with Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent.

  • Persistent-a persistence instance has a representation in the database and an identifier vlaue. It might have been saved or loaded, however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient.

  • Detached-a detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, ofcourse, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modification) persistent again. This fetaure enables a programming model for long running units of work that require user think-time. We call them application transaction, i.e., a unit of work from the point of view of the user.
Hibernate Life cycle

Life Cycle Operations

  • The Hibernate framework is used to mange the persistence of objects. It allows objects to be associated with data present in the tables.
  • It saves/modifies and inserts records in the database tables based on values in these objects and the operations performed on them using the Hibernate interfaces.
  • Saving Objects
    • Creating an instance of a class you map with Hibernate mapping does not automatically persist the object to the database until you save the object with a valid Hibernate session.
    • An object remains to be in "transient" state until it is saved and moved into "persistent" state.
    • The class of the object that is being saved must have a mapping file (myclass.hbm.xml).
    • Methods to save objects provided by Session interface.
      • public Serializable save( Object object)
      • public void save (String entityName, Object object, Serializable id)
  • Loading Objects
    • Used for loading objects from the database
    • load(..) method requires object's primary key as an identifier
    • Each load(..) method also requires which domain class or entity name to use to find the object with the id
    • The returned object, which is returned as Object type, needs to be type-casted to the domain class
      • public Object load(Class theClass , Serializable id)
  • load() v/s get()
    • Only use the load() method if you are sure that the object exists
    • load() method will throw an exception if the unique id is not found in the database
    • If you are not sure that the object exists, then use one of the get() methods
    • get() method will return null if the unique id is not found in the database

    • public Object get (Class theClass, Serializable id)
      Person person = (Person) session.get(Person.class, id);
      if (person == null){
           logger.info("Person is not found for id "+ id);
      }
  • Updating Objects
    • Used for updating object's state
    • Methods to save objects provided by Session interface
      • public void update( Object object)
      • public void saveOrUpdate( Object object) - This method will update the record if it exists in the database. Otherwise will insert a new record.
  • Deleting Objects
    • Removes an Object from the Database.
      • public void delete( Object object)

Object-relational impedance mismatch

MismatchDescription
GranularitySometimes you will have an object model which has more classes than the number of corresponding tables in the database.
InheritanceRDBMSs do not define anything similar to Inheritance which is a natural paradigm in object-oriented programming languages.
IdentityA RDBMS defines exactly one notion of 'sameness': the primary key. Java, however, defines both object identity (a==b) and object equality (a.equals(b)).
AssociationsObject-oriented languages represent associations using object references where as am RDBMS represents an association as a foreign key column.
NavigationThe ways you access objects in Java and in a RDBMS are fundamentally different.

org.hibernate.classic
Interface Lifecycle


public interface Lifecycle

Provides callbacks from the Session to the persistent object. Persistent classes may implement this interface but they are not required to.

onSave: called just before the object is saved
onUpdate: called just before an object is updated, ie. when Session.update() is called
onDelete: called just before an object is deleted
onLoad: called just after an object is loaded

onLoad() may be used to initialize transient properties of the object from its persistent state. It may not be used to load dependent objects since the Session interface may not be invoked from inside this method.

A further intended usage of onLoad()onSave() and onUpdate() is to store a reference to the Session for later use.

If onSave()onUpdate() or onDelete() return VETO, the operation is silently vetoed. If a CallbackException is thrown, the operation is vetoed and the exception is passed back to the application.

Note that onSave() is called after an identifier is assigned to the object, except when identity column key generation is used.

See Also:
CallbackException

Field Summary
static booleanNO_VETO
          Return value to accept the action (false)
static booleanVETO
          Return value to veto the action (true)

Method Summary
 booleanonDelete(Session s)
          Called when an entity is deleted.
 voidonLoad(Session s, Serializable id)
          Called after an entity is loaded.
 booleanonSave(Session s)
          Called when an entity is saved.
 booleanonUpdate(Session s)
          Called when an entity is passed to Session.update().

Field Detail

VETO

public static final boolean VETO
Return value to veto the action (true)
See Also:
Constant Field Values

NO_VETO

public static final boolean NO_VETO
Return value to accept the action (false)
See Also:
Constant Field Values
Method Detail

onSave

public boolean onSave(Session s)
               throws CallbackException
Called when an entity is saved.
Parameters:
s - the session
Returns:
true to veto save
Throws:
CallbackException

onUpdate

public boolean onUpdate(Session s)
                 throws CallbackException
Called when an entity is passed to Session.update(). This method is not called every time the object's state is persisted during a flush.
Parameters:
s - the session
Returns:
true to veto update
Throws:
CallbackException

onDelete

public boolean onDelete(Session s)
                 throws CallbackException
Called when an entity is deleted.
Parameters:
s - the session
Returns:
true to veto delete
Throws:
CallbackException

onLoad

public void onLoad(Session s,
                   Serializable id)
Called after an entity is loaded. It is illegal to access the Session from inside this method. However, the object may keep a reference to the session for later use.
Parameters:
s - the session
id - the identifier
Example : 


import org.hibernate.*;
import org.hibernate.cfg.*;
public class ClientProgram { 
    public static void main(String[] args)
    {
        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml"); 
        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
         // Transient state_____start
        Product p=new Product();
        p.setProductId(101);
        p.setProName("iPhone");
        p.setPrice(25000);
         // Transient state_____end
         // Persistent state_____start
        Transaction tx = session.beginTransaction();
        session.save(p);
        System.out.println("Object saved successfully.....!!");
        tx.commit();
         // Persistent state_____end  
        session.close();
        factory.close();
    }
Note :  
see the above client program, line numbers 16 to 19 we just loaded the object and called the corresponding setter methods, its not related to the database rowif you see, line number 24 we called save method in the Session Interface, means the object is now having the relation with the databaseif we want to convert the object from Transient state to Persistent state we can do in 2 waysBy saving that object like aboveBy loading object from databaseIf we do any modifications all the changes will first applied to the object in session cache only (Let__ we do the modifications 5 times, then 5 times we need to save the changes into the database right, which means number of round trips from our application to database will be increased, Actually if we load an object from the database, first it will saves in the cache-memory so if we do any number of changes all will be effected at cache level only and finally we can call save or update method so with the single call of save or update method the data will be saved into the database.If we want to save an object into database then we need to call any one of the following 3 methodssave()persist()saveOrUpdate()i will explain about persist, saveOrUpdate methods later….If we want to load an object from database, then we need to call either load() or get() methodsTransient:One newly created object,with out having any relation with the database, means never persistent, not associated with any Session object. Ex: – Account account = new Account();• account is a transient object account is a transient object . Hibernate is aware of, and managing, the object• id Has a database id– Already existing object retrieved from the database– Formerly transient object about to be saved Formerly transient object about to be saved• This is the only state where objects are saved to the database–  Modifications made in other states are NOT saved to the database while the object remains in that state– Changes to objects in a persistent state are automatically saved to the database without invoking session persistence methods database without invoking session persistence methods• Objects are made persistent through calls against the Hibernate session– session.save(account); – session.lock(account);– session.update(account); – session.merge(account); Session session = SessionFactory getCurrentSession(); SessionFactory.getCurrentSession();// ‘transient’ state – Hibernate is NOT aware that it existsAccount account Account account = new Account(); new Account();// transition to the ‘persistent’ state. Hibernate is NOW // aware of the object and will save it to the databasesession.saveOrUpdate(account);// modification of the obj yet will automatically be// saved because the object is in the ‘persistent’ stateaccount.setBalance(500);session.getTransaction().commit(); Persistent:   Having the relation with the database, associated with a unique Session objectDetached: previously having relation with the database [persistent ], now not associated with any Session see the next sessions for the better understanding of the life cycle states of pojo class object(s) the hibernate. Removed StateSession session = SessionFactory.getCurrentSession();// retrieve account with id 1. account is returned in a ‘persistent’ stateAccount account = session.get(Account.class, 1);// transition to the ‘removed’ state Hibernate deletes the // transition to the ‘removed’ state. Hibernate deletes the// database record, and no longer manages the objectsession.delete(account);// f modi ication is ignored by Hibernate since it is in the ‘removed’ stateaccount.setBalance(500);// commit the transactionsession.getTransaction().commit(); // notice the Java object is still alive, though deleted from the database.// stays alive until developer sets to null, or goes out of scope // stays alive until developer sets to null, or goes out of scopeaccount.setBalance(1000); // commit the transactionDetached State :   Session session1 = SessionFactory.getCurrentSession();// retrieve account with id 1. account is returned in a ‘persistent’ stateAccount account = session1.get(Account.class, 1);// transition to the ‘detached’ state. Hibernate no longer manages the objectsession1.close();// modification is ignored by Hibernate since it is in the ‘detached’// state, but the account still represents a row in the databaseaccount tB l (500) t.setBalance(500);// re-attach the object to an open session, returning it to the ‘persistent’// state and allowing its changes to be saved to the databaseSession session2 = SessionFactory getCurrentSession(); Session session2 = SessionFactory.getCurrentSession();session2.update(account);// commit the transactionsession2.getTransaction().commit();

Benefits of ORM/Hibernate : 

  • The SQL code / statements in the application can be eliminated without writing complex JDBC / Entity Bean code.
  • Distributed transaction can simply be performed by using ORM tools.
  • Hibernate is an open source ORM tool and a robust framework to perform OR Mapping.
  • Without much of SQL knowledge, one can master Hibernate easily.
  • Caching objects
  • Executing SQL statements later, when needed
  • Never updating unmodified objects
  • Efficient Collection Handling
  • Rolling two updates into one
  • Updating only the modified columns
  • Outer join fetching
  • Lazy collection initialization
  • Lazy object initialization
  • Transparent persistence & retrieval of objects
  • Persistence of associations and collections
  • Guaranteed uniqueness of an object (within a session).
  • O-R mapping using ordinary JavaBeans
  • Can set attributes using private fields or private setter methods
  • Lazy instantiation of collections (configurable)
  • Polymorphic queries, object-oriented query language
  • Cascading persist & retrieve for associations, including collections and many-to-many
  • Transaction management with rollback
  • Can integrate with other container-provided services.

Why Hibernate and not JDBC?

  • JDBC maps Java classes to database tables (and from Java data types to SQL data types)
  • Hibernate automatically generates the SQL queries.
  • Hibernate provides data query and retrieval facilities and can significantly reduce development time otherwise spent with manual data handling in SQL and JDBC.
  • Makes an application portable to all SQL databases.
Hibernate vs. JDBC (an example)
JDBC tuple insertion
st.executeUpdate("INSERT INTO book VALUES("Harry Potter","J.K.Rowling"));
Hibernate tuple insertion
session.save(book1);

High-Level View

Hibernate High level view

Minimal Architecture

  • The "minimal" architecture has the application manage its own JDBC connections and provide those connections to Hibernate; additionally the application manages transactions for itself.
Minimal Architecture

Comprehensive Architecture

  • The "comprehensive" architecture abstracts the application away from the underlying JDBC/JTA APIs and allows Hibernate to manage the details.
Comprehensive Architecture
Drawbacks of Using Hibernate  
  • High Level abstraction obscuring what is happening under the hood.
  • Runs on top of JDBC.
  • Support for Hibernate on Internet is not sufficient.
  • For complex data, mapping from Object-to-tables and vise versa reduces performance and increases time of conversion.
  • Anybody wanting to maintain application using Hibernate will need to know Hibernate.
  • Hibernate does not allow some type of queries which are supported by JDBC .

Hibernate Caching:

Hibernate use caching to maintain the performance of an application. The caching lie between the application and the database to avoid the number of hits to database, it provide better performance for critical applications.
Hibernate caching



There are 3 type of cache use by hibernate:

  • First-level cache
  • Second-level cache
  • Query-level cache

First-level Cache

  • The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database.
  • If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as possible to reduce the number of update SQL statements issued. If you close the session, all the objects being cached are lost and either persisted or updated in the database.

Second-level Cache

  • Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. The second-level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions.
  • Any third-party cache can be used with Hibernate. An 
    org.hibernate.cache.CacheProvider
     interface is provided, which must be implemented to provide Hibernate with a handle to the cache implementation.
  • Second-level cache, cache the information across different session objects whereas in first-level cache information is cache only within one session object.
Concurrency Strategies In Second-level Cache
  • Transactional: Use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.
  • Read-write: Again use this strategy for read-mostly data where it is critical to prevent stale data in concurrent transactions,in the rare case of an update.
  • Nonstrict-read-write: This strategy makes no guarantee of consistency between the cache and the database. Use this strategy if data hardly ever changes and a small likelihood of stale data is not of critical concern.
  • Read-only: A concurrency strategy suitable for data which never changes. Use it for reference data only.
Example Of Second-level Cache using EhCache
  • You need to download and add ehcache-core-2.4.2 jar into your classpath.
  • Add property 'cache.use_second_level_cache' in to hibernate.cfg.xml file and give 'true' as value to enable second level cache.
  • Add property 'cache.provider_class' into hibernate.cfg.xml file and give 'org.hibernate.cache.EhCacheProvider' as value
hibernate.cfg.xml file
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-configuration SYSTEM   
  3. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  4.   
  5. <hibernate-configuration>  
  6.    <session-factory>  
  7.    <property name="hibernate.dialect">   
  8.     org.hibernate.dialect.MySQLDialect </property>  
  9.    <property name="hibernate.connection.driver_class">   
  10.     com.mysql.jdbc.Driver </property>  
  11.   
  12.    <!-- Assume hibernatedb as the database name -->  
  13.    <property name="hibernate.connection.url">   
  14.     jdbc:mysql://localhost/hibernatedb </property>  
  15.    <property name="hibernate.connection.username">   
  16.     root </property>  
  17.    <property name="hibernate.connection.password">   
  18.     root </property>  
  19.      
  20.    <!-- Enable the second-level cache,   
  21.         here EhCache is used for caching-->  
  22.    <property name="cache.use_second_level_cache">  
  23.         true  
  24.     </property>  
  25.    <property name="cache.provider_class">  
  26.     org.hibernate.cache.EhCacheProvider</property>  
  27.      
  28.    <!-- Echo all executed SQL to stdout -->  
  29.     <property name="show_sql">true</property>  
  30.       
  31.    <!-- Drop and re-create the   
  32.         database schema on startup -->  
  33.    <property name="hbm2ddl.auto">create</property>    
  34.      
  35.    <!-- Names the annotated entity class -->  
  36.     <mapping class="com.tkhts.Student"/>  
  37.   
  38.    </session-factory>  
  39. </hibernate-configuration>  
Student.java file
  1. package com.tkhts; 
  2.   
  3. import javax.persistence.Cacheable;  
  4. import javax.persistence.Entity;  
  5. import javax.persistence.GeneratedValue;  
  6. import javax.persistence.GenerationType;  
  7. import javax.persistence.Id;  
  8. import javax.persistence.Table;  
  9.   
  10. import org.hibernate.annotations.Cache;  
  11. import org.hibernate.annotations.CacheConcurrencyStrategy;  
  12.   
  13. @Entity  
  14. @Cacheable //this annotation is use for enabling cache  
  15. @Cache(usage=CacheConcurrencyStrategy.READ_ONLY)   
  16. //this annotation is use to   
  17. //define Cache Concurrency Strategy  
  18.   
  19. @Table(name="STUDENT")  
  20. public class Student {  
  21.     @Id  
  22.     @GeneratedValue(strategy=GenerationType.AUTO)  
  23.     private int id;  
  24.     private String name;  
  25.     public int getId() {  
  26.         return id;  
  27.     }  
  28.     public void setId(int id) {  
  29.         this.id = id;  
  30.     }  
  31.     public String getName() {  
  32.         return name;  
  33.     }  
  34.     public void setName(String name) {  
  35.         this.name = name;  
  36.     }  
  37. }  
Test.java file
  1. package com.tkhts.test;  
  2.   
  3. import java.util.List;  
  4.   
  5. import org.hibernate.Query;  
  6. import org.hibernate.Session;  
  7. import org.hibernate.SessionFactory;  
  8. import org.hibernate.cfg.Configuration;  
  9.   
  10. import com.tkhts.Student;  
  11.   
  12. public class Test {  
  13.       
  14.     public static void main(String[] args) {  
  15.         SessionFactory sessionFactory = new  
  16.             Configuration().configure()  
  17.             .buildSessionFactory();  
  18.           
  19.         /*creating first session object  
  20.         to get data from Student table*/  
  21.         Session session=sessionFactory.openSession();  
  22.         session.beginTransaction();  
  23.         Student student1=  
  24.         (Student)session.get(Student.class, 1);  
  25.         session.getTransaction().commit();  
  26.         session.close(); //first session object closed  
  27.           
  28.         /*creating second session  
  29.             object to get data from Student table*/  
  30.         Session session2=sessionFactory.openSession();  
  31.         session2.beginTransaction();  
  32.         Student student2=  
  33.         (Student)session2.get(Student.class, 1);   
  34.         session2.getTransaction().commit();  
  35.         session2.close();   
  36.             //second session object closed  
  37.         }  
  38. }  
Output On console with Second-level cache
  1. SLF4J: Failed to load class  
  2.         "org.slf4j.impl.StaticLoggerBinder".  
  3. SLF4J: Defaulting to no-operation  
  4.         (NOP) logger implementation  
  5. SLF4J: See   
  6.     http://www.slf4j.org/codes.html#StaticLoggerBinder   
  7.     for further details.  
  8.     Hibernate: select student0_.id   
  9.     as id0_0_, student0_.name   
  10.     as name0_0_ from EMPLOYEE   
  11.     student0_ where student0_.id=?  
Note : In Second-level cache, information is cached across different session objects thats why only one select query is performed by hibernate. shown in output.
Output On console without Second-level cache
  1. SLF4J: Failed to load class  
  2.         "org.slf4j.impl.StaticLoggerBinder".  
  3. SLF4J: Defaulting to no-operation  
  4.         (NOP) logger implementation  
  5. SLF4J: See   
  6.     http://www.slf4j.org/codes.html#StaticLoggerBinder   
  7.     for further details.  
  8.     Hibernate: select student0_.id   
  9.         as id0_0_, student0_.name as   
  10.     name0_0_ from STUDENT student0_   
  11.     where student0_.id=?  
  12.     Hibernate: select student0_.id   
  13.     as id0_0_, student0_.name as   
  14.     name0_0_ from STUDENT student0_   
  15.     where student0_.id=?  
Note : In above output, information is not cached across different session objects thats why two select query is performed by hibernate. shown in output.

Cache Provider

Cache
read-only
nonstrict-read-write
read-write
transactional
Hashtable (not intended for production use)YesYesYes
EHCacheYesYesYesYes
OSCacheYesYesYes
SwarmCacheYesYes
JBoss Cache 1.xYesYes
JBoss Cache2YesYes

Hibernate Configuration in Eclipse

  • Step-1 Download hibernate-distribution-3.6.4.Final from http://www.hibernate.org/downloads
  • Step-2 Add below given jar files into classpath by rightclick on project >> properties >> java build path >> add library >> choose user library from the list >> click to user libraries >> click to new tab >> enter the user library name and click ok >> choose your library and click to add jars tab.
    • hibernate3.jar
    • antlr-2.7.6.jar
    • common-collections-3.1.jar
    • dom4j-1.6.1.jar
    • javassist-3.12.0.GA.jar
    • jta-1.1.jar
    • sl4j-api-1.6.1.jar
    • hibernate-jpa-2.0-api-1.0.0.Final.jar
    • mysql-connector-java-5.0.8-bin.jar download it from
  • http://dev.mysql.com/downloads/connector/j/5.0.html 
  • Step-3 Create XML file by right-click on project src folder >> New >> other >> XML >> XML file >> enter file name hibernate.cfg.xml >> finish.

  • Hibernate XML file

  • Step-4 Create another XML file by right-click on project src folder >> New >> other >> XML >> XML file >> enter file name Employee.hbm.xml >> finish.

  • Hibernate XML file next

  • Step-5 Create java class by right-click on project >> New >> class >> class name >> finish.

  • Adding Hibernate class

  • Step-6 Create another java class by right-click on project >> New >> class >> class name >> finish.

  • Adding Hibernate class next

Simple Example Of Hibernate  :   hibernate.cfg.xml file

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-configuration SYSTEM   
  3. "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">  
  4.   
  5. <hibernate-configuration>  
  6.    <session-factory>  
  7.    <property name="hibernate.dialect">   
  8.    org.hibernate.dialect.MySQLDialect </property>  
  9.    <property name="hibernate.connection.driver_class">   
  10.    com.mysql.jdbc.Driver </property>  
  11.   
  12.    <!-- Assume hibernatedb as the database name -->  
  13.    <property name="hibernate.connection.url">   
  14.    jdbc:mysql://localhost/hibernatedb </property>  
  15.    <property name="hibernate.connection.username">  
  16.    root  
  17.    </property>  
  18.    <property name="hibernate.connection.password">  
  19.    root  
  20.    </property>  
  21.      
  22.    <!-- Echo all executed SQL to stdout -->  
  23.     <property name="show_sql">true</property>  
  24.       
  25.    <!-- Drop and re-create the database   
  26.         schema on startup -->  
  27.    <property name="hbm2ddl.auto">create</property>    
  28.   
  29.    <!-- List of XML mapping files -->  
  30.    <mapping resource="Employee.hbm.xml"/>  
  31.   
  32.    </session-factory>  
  33. </hibernate-configuration>  
Employee.java file
  1. package com.tkhts;  
  2.   
  3. public class Employee {  
  4.       
  5.     private int id;  
  6.     private String firstName;  
  7.     private String lastName;  
  8.     private int salary;  
  9.   
  10.     public Employee(String firstName,   
  11.             String lastName, int salary){  
  12.         this.firstName = firstName;  
  13.         this.lastName = lastName;  
  14.         this.salary = salary;  
  15.     }  
  16.       
  17.     public int getId() {  
  18.         return id;  
  19.     }  
  20.     public void setId(int id) {  
  21.         this.id = id;  
  22.     }  
  23.     public String getFirstName() {  
  24.         return firstName;  
  25.     }  
  26.     public void setFirstName(String firstName) {  
  27.         this.firstName = firstName;  
  28.     }  
  29.     public String getLastName() {  
  30.         return lastName;  
  31.     }  
  32.     public void setLastName(String lastName) {  
  33.         this.lastName = lastName;  
  34.     }  
  35.     public int getSalary() {  
  36.         return salary;  
  37.     }  
  38.     public void setSalary(int salary) {  
  39.         this.salary = salary;  
  40.     }  
  41. }  
Employee.hbm.xml file
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <!DOCTYPE hibernate-mapping PUBLIC   
  3.  "-//Hibernate/Hibernate Mapping DTD//EN"  
  4.  "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">   
  5.    
  6. <hibernate-mapping>  
  7.  <class name="com.tkhts.Employee"  
  8.     table ="EMPLOYEES_TABLE">  
  9.     <id name="id" column="ID" type="int">  
  10.         <generator class="native"></generator>  
  11.     </id>  
  12.     <property name="firstName"  
  13.         column="first_name"  
  14.             type="string"></property>  
  15.     <property name="lastName" column="last_name"  
  16.         type="string"></property>  
  17.     <property name="salary" column="salary"  
  18.         type="int"></property>  
  19.  </class>  
  20.    
  21. </hibernate-mapping>  
  22.           
TestEmployee.java file
  1. package com.tkhts;  
  2.   
  3. import org.apache.log4j.chainsaw.Main;  
  4. import org.hibernate.HibernateException;  
  5. import org.hibernate.Session;  
  6. import org.hibernate.SessionFactory;  
  7. import org.hibernate.Transaction;  
  8. import org.hibernate.cfg.Configuration;  
  9.   
  10. public class TestEmployee {  
  11.     private static SessionFactory sesssionFactory;  
  12.     public static void main(String args[]){  
  13.           
  14.         sesssionFactory = new   
  15.         Configuration().configure().buildSessionFactory();  
  16.         TestEmployee employ = new TestEmployee();  
  17.         employ.addEmployee("abc""xyz", 100000);  
  18.         // pass EmployeeID and salary as  
  19.         // parameter to deleteEmployee   
  20.         method to delete the employee  
  21.         // employ.deleteEmployee(1, 1200000);  
  22.     }  
  23.       
  24.     public void addEmployee  
  25.         (String fName,String lName, int salary){  
  26.         Session session = sesssionFactory.openSession();  
  27.         Transaction tx = null;  
  28.         tx = session.beginTransaction();  
  29.         Employee emp = new Employee(fName, lName, salary);  
  30.         session.save(emp);  
  31.         tx.commit();  
  32.     }  
  33.       
  34.       
  35.     /* Method to UPDATE salary for an employee */  
  36.        public void deleteEmployee  
  37.         (Integer EmployeeID, int salary ){  
  38.           Session session = sesssionFactory.openSession();  
  39.           Transaction tx = null;  
  40.           try{  
  41.              tx = session.beginTransaction();  
  42.              Employee employee = (Employee)session.get  
  43.                 (Employee.class, EmployeeID);   
  44.         // This method set the salary of employee  
  45.         // employee.setSalary( salary );  
  46.         session.delete(employee);   
  47.              tx.commit();  
  48.           }catch (HibernateException e) {  
  49.              if (tx!=null) tx.rollback();  
  50.              e.printStackTrace();   
  51.           }  
  52.           catch(Exception e){  
  53.               if (tx!=null) tx.rollback();  
  54.                  e.printStackTrace();   
  55.           }  
  56.           finally {  
  57.              session.close();   
  58.           }  
  59.        }  
  60. }  
Output On Console
  1. SLF4J: Failed to load class  
  2.     "org.slf4j.impl.StaticLoggerBinder".  
  3. SLF4J: Defaulting to no-operation   
  4.     (NOP) logger implementation  
  5. SLF4J: See   
  6.     http://www.slf4j.org/codes.html#StaticLoggerBinder   
  7.         for further details.  
  8. Hibernate: insert into EMPLOYEES_TABLE   
  9. (first_name, last_name, salary) values (?, ?, ?)  
  10.           
Table in Mysql
Hibernate Output
1.What is ORM ?
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What does ORM consists of ?
An ORM solution consists of the followig four pieces:
  • API for performing basic CRUD operations
  • API to express queries refering to classes
  • Facilities to specify metadata
  • Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ?
The ORM levels are:
  • Pure relational (stored procedure.)
  • Light objects mapping (JDBC)
  • Medium object mapping
  • Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5.Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
  • Improved productivity
    • High-level object-oriented API
    • Less Java code to write
    • No SQL to write
  • Improved performance
    • Sophisticated caching
    • Lazy loading
    • Eager loading
  • Improved maintainability
    • A lot less code to write
  • Improved portability
    • ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify?
Hibernate simplifies:
  • Saving and retrieving your domain objects
  • Making database column and table name changes
  • Centralizing pre save and post retrieve logic
  • Complex joins for retrieving related items
  • Schema creation from object model

7.What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:
Hibernate Mapping file

8.What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
  • Programmatic configuration
  • XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml?
Following are the important tags of hibernate.cfg.xml:
hibernate.cfg.xml

What is Hibernate N+1 Problems and its Solution 

Hibernate n+1 problems only comes for one to many relationship.
Let us see this problem by example – We have Department table with a one-to-many relationship with Employee. One Department may have many Employees.
Table Department
IDNAME
1Department 1
2Department 2
3Department 3


Table of Employee
----------------------------------------------------
ID         Department_id             Name
------------------------------------------------------
1                 1                    Employee Name 1
2                 1                    Employee Name 2
3                  1                   Employee Name 3


We have written the Hibernate Department Entity as below
package com.java.connect.model;
@Entity
public class Department {
    private Long id;
     
    @OneToMany
    private Employee[] Employees;
}

So now you want to print out all the details of Employee models. A native O/R implementation would SELECT all Department and then do N additional SELECT's for getting the information of Employee for each department.
-- To Get all Departments
SELECT * FROM Department;
-- To get each Employee, get Employee details SELECT * FROM Employee WHERE Employee.departmentId = ?
As you see, the N+1 problem can happen if the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned.
Solution for Hibernate N+1 Problem
Using HQL fetch join
You can use the fetch while using the HQL as below example.
?
1
from Department d join fetch d.employees Employee
Hibernate Generated SQL would be similer as –
?
1
SELECT * FROM Department d LEFT OUTER JOIN Employee e ON d.id = d.department_id
Using Criteria query
?
1
2
Criteria criteria = session.createCriteria(Department.class);
criteria.setFetchMode("employees", FetchMode.EAGER);
In both above cases, the query returns a list of Department objects with the Employee initialized, and only one query needs to be run to return all the Department and Employee information required.

Example 2:
Let's say you have a collection of Car objects (database rows), and each Car has a collection of Wheel objects (database rows). In other words, Car:Wheel is a 1-to-many relationship.
Now, let's say you need to iterate through all the cars, and for each one, print out a list of the wheels. The naive O/R implementation would do the following:
SELECT * FROM Cars;
And then for each Car:
SELECT * FROM Wheel WHERE CarId = ?
In other words, you have one select for the Cars, and then N additional selects, where N is the total number of cars.
Alternatively, one could get all wheels and perform the lookup's in memory:
SELECT * FROM Wheel
This reduces the number of round-trips to the database from N+1 to 2.
Most ORM tools give you several ways to prevent N+1 selects.
What is the difference between save() and persist() method in Hibernate? (detailed answer)
Main difference between save() and persist() method is that, save returns a Serializable object while return type of persist() method is void, so it doesn't return anything. Here is a nice diagram which explains the state transition in Hibernate:
Hibernate interview questions for 2 to 3 years experienced Java programmers
What are different types of caches available in Hibernate? (detailed answer)
This is another common Hibernate interview question. Hibernate provides the out-of-box caching solution but there are many caches e.g. first level cache, second level cache and query cache. First level cache is maintained at Session level and cannot be disabled but the second level cache is required to be configured with external cache provider like EhCache.


What is the difference between first and second level cache in Hibernate? (detailed answer)
This is again follow-up of previous Hibernate interview question. The first level cache is maintained at Session level while the second level cache is maintained at SessionFactory level and shared by all sessions. You can read these books to learn more about caching in Hibernate.


Does Hibernate Session interface is thread-safe in Java? (detailed answer)
No, Session object is not thread-safe in Hibernate and intended to be used with-in single thread in the application.


Does SessionFactory is thread-safe in Hibernate? (detailed answer)
SessionFactory is both Immutable and thread-safe and it has just one single instance in Hibernate application. It is used to create Session object and it also provide caching by storing SQL queries stored by multiple session. The second level cache is maintained at SessionFactory level. This can be a difficult and tricky question for less experienced Java developers who are not familiar with thread-safety and Immutability.


What is different between Session and Sessionfactory in Hibernate? (detailed answer)
This is another popular Hibernate interview question, mostly at a telephonic round of interviews. The main difference between Session and SessionFactory is that former is a single-threaded, short-lived object while later is Immutable and shared by all Session. It also lives until the Hibernate is running. Another difference between Session and SessionFactory is that former provides first level cache while SessionFactory provides the Second level cache.


What is criterion query in hibernate? (detailed answer)
Criteria is a simplified API for retrieving entities by composing Criterion objects also known as Criterion query. This is a very convenient approach for functionality like "search" screens where you can filter data on multiple conditions as shown in the following example:
List books = session.createCriteria(Book.class)
.add(Restrictions.like("name", "java%") )
.add(Restrictions.like("published_year", "2015"))
.addOrder(Order.asc("name") )
.list();
This can be a tough question if you are not using Hibernate on a daily basis, I have interviewed several Java developers who have used Hibernate but doesn't know about Criterion query or API.


What are other ORM frameworks? Any alternative of Hibernate?
This is a general question, sometimes asked to start the conversation and other times to finish the interview. EJB and TopLink from Oracle are two of the most popular alternative to Hibernate framework.


What is the difference between save() and saveOrUpdate() method of Hibernate? (detailed answer)
Though both save() and saveOrUpdate() method is used to store object into Database, the key difference between them is that save can only INSERT records but saveOrUpdate() can either INSERT or UPDATE records.


What is difference between getCurrentSession() and openSession() in Hibernate? (detailed answer)
An interesting Hibernate interview question as you might have used both getCurrentSession() and openSession() to obtain an instance of Session object. I have left this question unanswered for you to answer or find an answer based on your experience.


What is Hibernate Query Language (HQL)? (detailed answer)
Hibernate query language, HQL is an object-oriented extension to SQL. It allows you to query, store, update, and retrieve objects from a database without using SQL. This question is also similar to the earlier question about Criterion query, Java developers who have not used Hibernate extensively will not know much about features like HQL and Criterion.


When do you use merge() and update() in Hibernate? (detailed answer)
This is one of the tricky Hibernate interview questions. You should use update() if you are sure that the Hibernate session does not contain an already persistent instance with the same id and use merge() if you want to merge your modifications at any time without considering the state of the session. 
What is Versioning in Hibernate?

How Versioning Works in Hibernate

  1. Version Column: You can add a version column to your entity class. This column will be used by Hibernate to track the version of the entity.

  2. Concurrency Control: When Hibernate performs a database operation (e.g., update), it checks the version number. If the version has changed since it was read, an exception is thrown (OptimisticLockException), indicating that someone else modified the data in the meantime.

Using @Version for Versioning

To enable versioning, follow these steps:

  1. Add a @Version field to the entity class.

  2. Hibernate will automatically manage the version number in the corresponding column in the database.

import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Version; @Entity public class Product { @Id private Long id; private String name; private double price; @Version private int version; // version column for optimistic locking // Constructors, Getters, and Setters public Product() {} public Product(Long id, String name, double price) { this.id = id; this.name = name; this.price = price; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } }

  • The @Version annotation marks the version field as the version column. This field is automatically updated with a version number whenever the entity is updated.

    The column
    version will be used by Hibernate to track the version of the entity and prevent concurrency issues.



  • 1Employee Name 3
























    2 comments:

    1. Wow! Thank you! I always needed to write on my website something like that. Can I include a portion of your post to my website?
      Oracle Enterprise Manager online online training
      Oracle Exadata online online training

      ReplyDelete
    2. Thanks for sharing this informative content , Great work
      Leanpitch provides online training in ICP CAT during this lockdown period everyone can use it wisely.
      ICP-CAT certification

      ReplyDelete

    Java 9 and Java11 and Java17, Java 21 Features

     Java 9 and Java11 and Java17 features along with explanation and examples in realtime scenarios Here's a detailed breakdown of Java 9, ...