Showing posts with label Hibernate. Show all posts
Showing posts with label Hibernate. Show all posts

Friday, April 7, 2017

Hibernate Interview Questions

1. What is the difference between openSession and getCurrentSession?

         openSession will open a new session and getCurrentSessiona will use an existing one which is in available in context.

2. What is the difference between get/load and createCriteria?   

         load will not hit database(because of fake object) and it will throw object not found exception if data not available.

         get will hit database and it will throw null if data is not available.

       createCriteria is a method of session interface and it will create a criteria object of persistence object of you requested class.

e.g : Criteria cr  = session.createCriteria(Employee.class)

3. Why we need to use hibernate ?

        1. HQL - You do not want to write query and it will be suitable to all database when we change in future.

        2. OOPS concept -   You will get oops concept since you are using table as entity in hibernate. So inheritance, encapsulation etc., all you will get.

         3. Caching Mechanism - First level cache and second level cache possible.

         4. Lazy loading - You can set when child has to be loaded while parent loading.

4. How many ways configure hibernate.config.xml file ?

        1. By using xml file (hibernate.config.xml)
        2.By using setProperty() method of configuration
        3.By using properties file

5. How you do hibernate pagination ?

    You can set the result per page wise. 

        Query query = session.createQuery("From Person");
        query.setFirstResult(0);
        query.setMaxResults(10);

ScrollableResults also we can use for pagination.

For more please check this stackoverflow link.

6. What is hibernate First level cache ?

1. First level cache is associated with session object.
2. Default it will enable and you can not disable it.
3. When we query for first time, it will get from DB and second time if you excecute the same query it will get from cache.

7. What is second level cache ?

Second level cache is associated with session Factory object. Actually it will reduce our database traffic. We have lot of option to enable second level cache in hibernate. But mostly all will use EHCache, since its fast and lightweight. It will support read only , read/write operation 

8. How to enable second level cache in hibernate ?

You can enable it through hibernate.cfg.xml. It look likes below.


<hibernate-configuration>
      <session-factory>
          <property  name=hibernate.cache.provider_class">
                     org.hibernate.cache.EHCacheProvider
          </property>
          <property name="net.sf.ehcache.configurationResourceName">ehcache.xml</property>
      </session-factory>
</hibernate-configuration>

9. What is evict method in hibernate ?

evict method will be useful, to remove session from first level cache.

Person t = (Person) session.load(Person.class, new Integer(1));
   
session.evict(t);

It will remove only t cached from particular session . But session.clear() remove all cached.

10. What is hibernate versioning ?

If you want to find how many times your Object was modified ,  then you should apply versioning in hibernate. Whenever you modified the object it will increment one number automatically.

11. How do you call aggregate functions in hibernate?

String hql = "select count(name) from Product";

Query query = session.createQuery(hql);
List listResult = query.list();

You can use all sum(), avg(), min(), max() etc.,

12. How to disable Hibernate first level cache ?

We can not disable hibernate first level cache and it will be enabled by default.

13. What are the interfaces available in hibernate ?

Session Interface

Session Factory Interface

Configuration Interface

Transaction Interface

Query and Criteria Interface

Thursday, April 21, 2016

Hibernate One to Many Relationship with Example

One to may relationship can occur between two tables and where one table row can have multiple matching rows from other table. In hibernate also same concept with the name of Entity.

How its occurring ?

As usual, by the help of primary key Foreign key relationship.

One To Many (XML Mapping)

We have taken two model classes to describing this relationship. Item class and ItemRecord class.

Item.java 


package com.javahit.items;

import java.util.HashSet;
import java.util.Set;

public class Item implements java.io.Serializable {

 private Integer itemId;
 private String itemCode;
 private String itemName;


 private Set<itemrecord> itemRecords = 
    new HashSet<itemrecord>(0);

 //getter setter
}

ItemRecord.java

package com.javahit.items;

import java.util.Date;

public class ItemRecord implements java.io.Serializable {

 private Integer itemRecordId;
 private Item item;
 private Float price;
 private Long volume;


 //getter & setter
}

Hibernate XML Mapping file

For the above two model classes we should create hibernate mapping files.Lets see , how its look like

item.hbm.xml


    
        
            
            
        
        
            
        
        
            
        
        
            
                
            
            
        
    

inverse = true specifies, which side the relationship(One to Many , Many to Many) should take care. Mostly it will be come with these two relationship only.

lazy specifies, whether to load child objects(tables) or not, while loading parent object.(tables).

fetch = "select" - do a lazy load for all collection and entities. Remaining possible strategies are below.
fetch = "join" - It will disable lazy load , so all collection and entities will be loaded always.
fetch = "batch-size" - You can mention batch size here to fetch collection and entity data.
fectch = "subselect" - It will make your collection group into a subselect.

itemRecord.hbm.xml


    
        
            
            
        
        
            
        
        
            
        

        
            
        
        
    

Hibernate Configuration xml

Now configure your two model classes hbm xml as well as db driver, userName, pwd etc details.



    com.mysql.jdbc.Driver
    jdbc:mysql://localhost:3310/testdb
    sa
    password
    org.hibernate.dialect.MySQLDialect
    true
    true
    
    



Store Data

This is our final java class file which contains hibernate configuration logic and one to many working code.

package com.javahit;

import java.util.Date;
import org.hibernate.Session;
import com.javahit.items.Item;
import com.javahit.items.ItemRecord;


public class StoreAndRetreive {
 public static void main(String[] args) {
 
 Configuration cfg=new Configuration();    
        cfg.configure("hibernate.cfg.xml");  
    
        SessionFactory sf=cfg.buildSessionFactory();    
        Session session=sf.openSession();    
        Transaction tx=session.beginTransaction();

 Item item = new Item();
        item.setItemCode("1001");
        item.setItemName("Item Name");
        session.save(item);
        
        ItemRecord itemRecords = new ItemRecord();
        itemRecords.setPrice(new Float("5.2"));
        itemRecords.setVolume(10L);
        
        itemRecords.setItem(item);        
        item.getItemRecords().add(itemRecords);

        session.save(itemRecords);

 tx.commit();
 System.out.println("Sucess");
 }
}

Wednesday, April 6, 2016

Inheritance in Hibernate

Hibernate have lot of good feature, in that Inheritance is one of the best. Its supports some of the following mapping strategies.

Single Table Per Class:
            Here both super class and sub class are mapped to same table. Another thing, one additional column need to mention to identify row is an instance of super class or sub class. 

Joined Sub Class:
            A separate table will be used for each class. The sub class table will store only the fields that are not present in the super class. So that in future, if you need to retrieve all data join need to performed on that two tables.

Table Per Class:
            A separate table will be used for each class. The sub class can store fields of super class also. So that no need to perform join to retrieve data, since sub class one row have all details.


Example of Single Table Per Class

            Already we have implemented Employee class. I have created below Skill class as a sub class of Employee.


public class Skill extends Employee {
private String skillName;
//Setter and Getter method
}

Now let’s see the mapping file for the additional field skillName. 


      
        
           
        
     

     
     
     
     
        
     


There is a new tag called discriminator column, which will store type information your current data.(Which class belongs to).


In our case we have created EMPLOYEE_TYPE as a discriminator and set the type to string. You can use int also. 

We have added new sub class element tag to mentioned added sub class to mention its fields and column. The subclass field skillName will be mapped to SKILL_NAME column.

session.getTransaction().begin();
Skill skill = new Skill();
skill.setFirstName("Test First Name");
skill.setLastName("Test Last Name");
skill.setSkillName("TestSkillName");
session.save(skill);
session.getTransaction().commit();


After executing this you will see below output.
Hibernate:
    drop table T_EMPLOYEE if exists
Hibernate:
    create table T_EMPLOYEE (
      ID bigint generated by default as identity,
      EMPLOYEE_TYPE varchar(255) not null,
      FIRST_NAME varchar(255),
      LAST_NAME varchar(255),
      SKILL_NAME varchar(255),
      primary key (ID)
)
Hibernate:
   insert into T_EMPLOYEE
       (ID, FIRST_NAME, LAST_NAME, SKILL_NAME, EMPLOYEE_TYPE)
   values
   null, ?, ?, ?, ’hibernate.entity.Skill’)

Example of Joined Sub Class
           
            Next we can see Joined sub class which definition already provided. See below mapping file,



   
    
     
   

        
        

      
           
       
      
    
            The Joined sub class tag will instruct hibernate to create table for the sub class of Skill and the table name is T_SKILL and added one new column for the purpose of accessing its parent table(Super class) T_EMPLOYEE. means, it will work as foreign key.


Once you execute this code, you will see below in console.


Hibernate:
      insert into T_EMPLOYEE
     (ID, FIRST_NAME, LAST_NAME, ID_ID_CARD)
     values
     (null, ?, ?, ?)

Hibernate:
     insert
     into
     T_SKILL
     (SKILL_NAME, ID_PERSON)
     values
     (?, ?)

Example of Table Per Class


            Next we can see table per class, its definition was provided already. see below mapping file,



 
  
   
    
   
   
   
   
  
   
    
   
  
 
You can see generator class as sequence , which will create a unique id for both table T_EMPLOYEE and T_SKILL. As usual Union-subclass tag will create a separate table T_SKILL whereas same column SKILL_NAME. 

After executing your code, you will see below in console tab.


Hibernate:
 call next value for hibernate_sequence
Hibernate:
 insert into T_PERSON (
 FIRST_NAME, LAST_NAME, ID)
values
   (?, ?, ?, ?)

Hibernate:
    call next value for hibernate_sequence

Hibernate:
    insert into T_SKILL (
 FIRST_NAME, LAST_NAME, FAV_PROG_LANG, ID)
values
   (?, ?, ?, ?, ?)