Hibernate

Hibernate Interview Questions
What is  Hibernate Caching ?

A tutorial on how to configure Ehcache as the second-level cache in Hibernate
name="hibernate.cache.provider_class">net.sf.ehcache.hibernate.EhCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">true</propertyEhCache is a very powerful  cache with a wide range of applications.In this tutorial we will configure and use Ehcache as the Hibernate's second-level cache.As an example will configure Ehcache for caching the tutorial categories and  all queries of  java-only website .
After downloading and installing Ehcache,first thing will be to add at Hiberntae configuration file -hibernate.cfg.xml- the following two properties:
<property >
Next,we must create the Ehcache configuration file where Ehcache's default cache ,the entities and queries that will be cached are defined.For your convinience you can name the configuration file "ehcache.xml" and place it in the same folder with hibernate.cfg.xml.The ehcache.xml must look something like this:
<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <diskStore path="C:\caching"/>
    <defaultCache
    maxElementsInMemory="10000"
    eternal="false"
    timeToIdleSeconds="600"
    timeToLiveSeconds="600"
    overflowToDisk="true" />
    <cache name="com.javaonly.model.Category"
      eternal="false"
    timeToLiveSeconds="600"
    overflowToDisk="true"
    />
           <cache
    name="com.javaonly.model.Category.subCategories"
    eternal="false"
    timeToLiveSeconds="600"
    overflowToDisk="true"
/>


<cache
        name="org.hibernate.cache.StandardQueryCache" maxElementsInMemory="10000"
        eternal="false"
        overflowToDisk="false" />
</ehcache>

A tutorial about many-to-one relationships on the same table using Hibernate
As a developer you may find your self in a situation where an entity may have many children entities of the same type.As an example consider the case where a Category may consists of many sub-Categories.It may be obvious that the previously mentioned example is a clear one-to-many/many-to-one relationship.Let 's see now how such a relationship can be implemented using Hibernate.

Beginning from the database side the category table will look something like this:
create table 'category '(

`id` int(11) NOT NULL AUTO_INCREMENT,
 `name_of_the_category` varchar(150) NOT NULL,
`parent_category` int(11) DEFAULT NULL,
 PRIMARY KEY (`id`),
KEY `name_of_the_category` (`name_of_the_category`),
KEY `FK_1` (`parent_category`),
CONSTRAINT `FK_1` FOREIGN KEY (`parent_category`) REFERENCES `category` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

In the above listing we created a database table named "Category",with fields: id ,name_of_the_category,parent_category and a foreign key between "parent_category" and "id" columns
The next step is to crate th POJO that will represent the database table:

public class Category {
private int id;
private String categoryName;
private Set subCategories;
private Category parentCategory;
public int getId() {
 return id;
}
public void setId(int id) {
this.id = id;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public Category getParentCategory() {
return parentCategory;
}
public void setParentCategory(Category parentCategory) {
this.parentCategory = parentCategory;
}
 public String toString(){
return getCategoryName();
}
public Set getSubCategories() {
return subCategories;
}
public void setSubCategories(Set subCategories) {
this.subCategories = subCategories;
}
}
Now that Category class is ready we move on to create the hibernate mapping file:
<hibernate-mapping> 
<class table="category" name="com.javaonly.model.Category">
<id type="int" name="id">  
<column name="id"></column>
<generator class="native"></generator>
</id>
<property type="string" name="categoryName">
<column not-null="true" length="150" name="name_of_the_category"></column>
 </property>
 <set inverse="true" cascade="all-delete-orphan" lazy="false" name="subCategories">
  <key column="parent_category"></key>  
  <one-to-many class="com.javaonly.model.Category">
  </one-to-many>
  </set>
  <many-to-one class="com.javaonly.model.Category" name="parentCategory">
  <column name="parent_category"></column>
 </many-to-one>
</class>
</hibernate-mapping>


In category table one-to-many relationship is expresed between ti id field and parent_category field.In the hibernate mapping file,this relationship is mapped between subcategories set and parentCategory property.Being more specific the one part of the relationship is mapped with set subCategories

<set inverse="true" cascade="all-delete-orphan" lazy="false" name="subCategories"> 
<key column="parent_category"></key>  
<one-to-many class="com.javaonly.model.Category">  
</one-to-many>
</set>

The many part of the relationship is expressed in hibernate wih:

<many-to-one name="parentCategory" class="com.javaonly.model.Category"> 
<column name="parent_category"></column>  
</many-to-one>

Learn how to map enum java type to MySQL enum type using hibernate
MySql database came's with an enum datatype that although is quite proprietery it can be easily mapped to a java enumeration type in hibernate.

In our example consider the case were we have created a table SIZES which contains a colum SIZE that is declared as enum type with values SMALL, MEDIUM and LARGE. Firstly we create the database table:
CREATE TABLE IF NOT EXISTS `sizes` (
  `id` int(10) NOT NULL DEFAULT '0',
  `size` enum('MEDIUM','LARGE','SMALL') DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
INSERT INTO `sizes` (`id`, `size`) VALUES
I
(0, 'SMALL');
The next step is to create the java enum type Size and the Sizes pojo class

package com.javaonly.model;
public enum Size {
LARGE("LARGE"), MEDIUM("MEDIUM"), SMALL("SMALL");
   String name;
   Size(String name) {
this.name = name;
}
   public String toString() {
       return name;
   }
   }

package com.javaonly.model;

public class Sizes {
private int idl;
    private Size size;
    public int getIdl() {
        return idl;
 }
    public void setIdl(int idl) {
        this.idl = idl;
    }
    public Size getSize() {
        return size;
    }
   public void setSize(Size size) {
this.size = size;
    }
    public String toString(){
        return size.toString();
    }
    }


Finally we create the hibernate mapping file
<?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.javaonly.model.Sizes" table="sizes">
        <id name="idl" type="integer" column="id">
<generator class="native"/>    
</id>
<property name="size" column="size">
<type name="org.hibernate.type.EnumType">
<param name="enumClass">com.javaonly.model.Size</param>
            </type>    
</property>
    </class>
</hibernate-mapping>

The important part  in the hibernate mapping file is the declaration of the property type.Hibernate comes with a class that represents the java enum type that  -among the other parameters- takes as a parameter the enumeration class which in this case is the com.javaonly.model.Size class
 a tutorial on what is and what should contain the HibernateUtil class
 When we are using  Hibernate it is considered quite good practice to have all the configuration code - such as the configuration of session etc- and all the methods that we will need -such as  methods for saving,deleting or updating- in order to interact with the database gathered in one class.HibernateUtil class is not a Hibernate's standard class and this is probably a good thing because developers can build it and customizing according to its application's needs. The below snippet show an implementation:

package com.javaonly.hibernate;
import org.hibernate.FlushMode;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
// Log the exception. 
System.err.println("Initial SessionFactory creation failed." + ex);
           throw new ExceptionInInitializerError(ex);
        }
    }

   public static SessionFactory getSessionFactory() {
return sessionFactory;
   }
   public static void beginViewTransaction() {
       sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().setFlushMode(FlushMode.NEVER);
   }
   public static String showMode() {
if (trasactionIsActive()) {
           return sessionFactory.getCurrentSession().getFlushMode().toString();
       }
return "NOT-ACTIVE";
   }
   public static void beginWriteTransaction() {
sessionFactory.getCurrentSession().beginTransaction();
sessionFactory.getCurrentSession().setFlushMode(FlushMode.AUTO);
   }
     // Determines whether the current transaction is active
    public static boolean trasactionIsActive() {
        return sessionFactory.getCurrentSession().getTransaction().isActive();
    }
      // Commits the hibernate transaction (if active).
    public static void commitTransaction() throws HibernateException {
        if (trasactionIsActive()) {
sessionFactory.getCurrentSession().getTransaction().commit();
        }
    }

// Rolls back current hibernate transaction (if active).

public static void rollbackTransaction() {
        if (trasactionIsActive()) {
sessionFactory.getCurrentSession().getTransaction().rollback();
}
   }
// Get's the current transaction's hashCode
    public static long transactionHashcode() {
        return sessionFactory.getCurrentSession().getTransaction().hashCode();
    }
}
A tutorial on how to create database tables from hibernate mapping files using hbm2ddl tool
There are times where it is more convinient  to  develop your appliation's model before creating the  corresponding database schema.For such cases hibernate comes with a very powerful tool that creates or updates  the database schema from the mapping files of the entities classes.In this tutorial will show you how you can use hbm2ddl tool to create the database schema.
 
In order to be able to use hbm2ddl tool we must set the "hibernate.hbm2ddl.auto" property to "create-drop".In other words add at the hibernate.cfg.xml file the following line:


<property name="hibernate.hbm2ddl.auto">create-drop</property>
The next and final step will be to create a class that will utilize SchemaExport class in order to create the database schema.
 
 import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.cfg.Configuration;
public class Test {
   public static void main(String args[]){
       Configuration cfg=new Configuration();
       cfg.configure("hibernate.cfg.xml");
         SchemaExport se=new SchemaExport(cfg);
        se.create(true, true);
    }
    }

A tutorial on how to configure connection pooling in hibernate

Using a connection pool for connecting and communicating with the database is considered one of the best practises in modern application development.That is because most connection pool  implementations are designed to manage effitiently connections (creating and deleting  connections,idle connections handling etc) and in general optimize the performance of the application
As for managing and caching JDBC connections Hibernate use c3p0,a very easy-to-use and powerful api for managing JDBC connection and statement pooling.
In order to configure connection pooling with c3p0 all you have to do is to add the follwing properties in the hibernate.cfg.xml and the appropriate jars in your application's classpath:

<property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">100</property>
        <property name="hibernate.c3p0.idle_test_period">3600</property>
        <property name="hibernate.c3p0.timeout">7200</property>

hibernate.c3p0.min_size is the mimum connections in the pool andhibernate.c3p0.max_size is the maximum number of connections in the pool.hibernate.c3p0.idle_test_period is the time in seconds that the pool will remain idle before validate and hibernate.c3p0.timeout is the pool's maximum idle time in seconds.

Schedule daily database backup with Hibernate and Quartz

A tutorial on how to configure Quartz and Hibernate and schedule daily database backup
Quartz API is an excellent choice for scheduling the execution of tasks and jobs.In this tutorial we will use Quartz in conjunction with hibernate to configure daily backup of a web application's database.
As an example consider the case where we need a backup of the database to be taken every day at midnight.

The first step will be to create the class that is going to be the task that will be executed by the Quartz scheduler.

package com.javaonly.jobs;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class DatabaseBackupJob implements Job {
public void execute(JobExecutionContext jec) throws JobExecutionException {
       Configuration cfg=new Configuration();
       cfg.configure("hibernate.cfg.xml");
SchemaExport se=new SchemaExport(cfg);
        se.setOutputFile("C:\\backup.sql");
        se.execute(true, true, false, false);
    }

}
 
As you can see in the above class used the SchemaExport class for exporting the sql file of the database..In order to configure hbm2ddl tool we must add the following property at the hibernate.cfg.xml file:

 <property name="hibernate.hbm2ddl.auto">create-drop</property>
Finally we will create a servlet context listener where we will configure the scheduler to execute the DataBaseBackupJob every day at midnight:
 package com.javaonly.listeners;
import org.quartz.CronTrigger;
import com.javaonly.jobs.DatabaseBackupJob;
import org.quartz.JobDetail;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.*;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.TriggerBuilder.newTrigger;

public class DatabaseBackupListener implements ServletContextListener {
    private Scheduler scheduler;
    public void contextInitialized(ServletContextEvent event) {
        try {
//initialize the scheduler factory
            SchedulerFactory schedulerFactory=new StdSchedulerFactory();
//get a scheduler
            scheduler = schedulerFactory.getScheduler();
//configure Database backup job
JobDetail job=newJob(DatabaseBackupJob.class).withIdentity("databaseBackup","group").build();
//create a cron type Trigger and schedule database backup to happen every day at midnight
            CronTrigger trigger = newTrigger()
    .withIdentity("trigger1", "group1")
    .withSchedule(cronSchedule("0 0 12 * * ?"))
.build();
scheduler.scheduleJob(job, trigger);
    scheduler.start();
        } catch (SchedulerException ex) {
Logger.getLogger(DatabaseBackupListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public void contextDestroyed(ServletContextEvent event) {
        try {
           scheduler.shutdown();
        } catch (SchedulerException ex) {
Logger.getLogger(DatabaseBackupListener.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
The only thing left now is to add the listener at the web.xml.At the web xml add the following snippet:
<listener>
        <listener-class>com.javaonly.DatabaseBackupListener</listener-class>
    </listener>
What’s the difference between load() and get()? 
load() vs. get() :-
load() 
get() 
Only use the load() method if you are sure that the object exists. 
If you are not sure that the object exists, then use one of the get() methods. 
load() method will throw an exception if the unique id is not found in the database. 
get() method will return null if the unique id is not found in the database. 
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked.  
get() will hit the database immediately. 

How can Hibernate be configured to access an instance variable directly and not through a setter method ?
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.

How can a whole class be mapped as immutable?
 
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
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.


   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.

What are the benefits does HibernateTemplate provide?

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.