Check if a class extends another at Runtime : Java

Summary :

  • If you want to know whether or not a Class extends another, use Class#isAssignableFrom(Class)
  • Class#isAssignableFrom(Class) also returns true if both classes are same
  • To find if an object is instance of a class use instanceof operator
  • To know if a class is direct sub class of another class then use Class#getSuperClass().equals(Class)

Setup :

We have an interface MyInterface and three classes MyBaseClass, MySubClass and SomeOtherClass with the below hierarchy.

interface MyInterface {
}

class MyBaseClass implements MyInterface {
}

class MySubClass extends MyBaseClass {
}

class SomeOtherClass {
}   

Tests:

   

public class Test {
  
  public static void main( String[] args ) {
    
    /*
     * Checking if a class is same as or is a superclass or superinterface
     * 
     * of another class (the class in parameter)
     */
    System.out.println( MyBaseClass.class.isAssignableFrom( MyBaseClass.class ) );// true : same class
    System.out.println( MyBaseClass.class.equals( MyBaseClass.class ) );// true : same class
    System.out.println( MyBaseClass.class.isAssignableFrom( MySubClass.class ) );// true : superclass
    System.out.println( MyInterface.class.isAssignableFrom( MySubClass.class ) );// true : superinterface
    System.out.println( MyBaseClass.class.isAssignableFrom( SomeOtherClass.class ) );// false : the two classes has no relation
    System.out.println( MySubClass.class.isAssignableFrom( MyBaseClass.class ) );// false : MySubClass is not the superclass
    
    /*
     * Checking if a object is instance of a class
     */
    
    IMyInterface object = new MyBaseClass( );
    System.out.println( object instanceof MyInterface ); // true
    System.out.println( object instanceof MyBaseClass ); // true
    System.out.println( object instanceof MySubClass ); // false
    System.out.println( object instanceof SomeOtherClass );// false
    
    /*
     * check if a class is direct superclass of another
     */
    
    System.out.println( MySubClass.class.getSuperclass( ).equals( MyInterface.class ) );// false : its not a directsuper class, interface
    System.out.println( MyBaseClass.class.getSuperclass( ).equals( MyInterface.class ) );// false : its not a directsuper class, interface
    System.out.println( MySubClass.class.getSuperclass( ).equals( MyBaseClass.class ) );// true : MyBaseClass is extending MySubClass
  }
}
   

Full code :

   

public class Test {
  
  public static void main( String[] args ) {
    
    /*
     * Checking if a class is same as or is a superclass or superinterface
     * 
     * of another class (the class in parameter)
     */
    System.out.println( MyBaseClass.class.isAssignableFrom( MyBaseClass.class ) );// true : same class
    System.out.println( MyBaseClass.class.equals( MyBaseClass.class ) );// true : same class
    System.out.println( MyBaseClass.class.isAssignableFrom( MySubClass.class ) );// true : superclass
    System.out.println( MyInterface.class.isAssignableFrom( MySubClass.class ) );// true : superinterface
    System.out.println( MyBaseClass.class.isAssignableFrom( SomeOtherClass.class ) );// false : the two classes has no relation
    System.out.println( MySubClass.class.isAssignableFrom( MyBaseClass.class ) );// false : MySubClass is not the superclass
    
    /*
     * Checking if a object is instance of a class
     */
    
    IMyInterface object = new MyBaseClass( );
    System.out.println( object instanceof MyInterface ); // true
    System.out.println( object instanceof MyBaseClass ); // true
    System.out.println( object instanceof MySubClass ); // false
    System.out.println( object instanceof SomeOtherClass );// false
    
    /*
     * check if a class is direct superclass of another
     */
    
    System.out.println( MySubClass.class.getSuperclass( ).equals( MyInterface.class ) );// false : its not a directsuper class, interface
    System.out.println( MyBaseClass.class.getSuperclass( ).equals( MyInterface.class ) );// false : its not a directsuper class, interface
    System.out.println( MySubClass.class.getSuperclass( ).equals( MyBaseClass.class ) );// true : MyBaseClass is extending MySubClass
  }
}

interface MyInterface {
}

class MyBaseClass implements MyInterface {
}

class MySubClass extends MyBaseClass {
}

class SomeOtherClass {
}

      
   

superclass "javax.servlet.http.HttpServlet" not found on Java Build Path - solution

You might (normally) get the error following error on a dynamic java web project created through maven on Eclipse IDE. The solution is simple :
Error :
The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path   
Error Location :
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Solution 1)
Edit pom.xml to include servlet-api-x.x.jar in your dependencies:
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.1</version>
  <scope>provided</scope>
</dependency>   
Solution 2)
Go to Project->Properties->Target Runtimes . And add your server container eg. : Apache Tomcat


Java Obsfucate Password - Replace with asterisk

Obsfucate password : 

Rreplace everything except first and last character by asterisk ( * ), if  the password is less than ALLOWED_LENGTH characters long obfuscate it entirely i.e., prints asterisks

Code :
   
//Test 
System.out.println( getObfuscatedPassword( "" ) ); //returns null
System.out.println( getObfuscatedPassword( "pwdd" ) ); //returns ****
System.out.println( getObfuscatedPassword( "mySecurePassword" ) ); // returns m**************d


//Method 
public static String getObfuscatedPassword( String password ) {
   
   int ALLOWED_LENGTH = 5;
   
   if ( null == password || "".equals( password.trim( ) ) ) {
    return null;
   }
   
   StringBuilder builder = new StringBuilder( );
   
   if ( password.length( ) < ALLOWED_LENGTH ) {
   
    for ( int i = password.length( ); i != 0; i-- ) {
     builder.append( "*" );
    }
   
    return builder.toString( );
   }
   
   builder.append( password.charAt( 0 ) );
   
   for ( int i = password.length( ) - 2; i != 0; i-- ) {
    builder.append( "*" );
   }
   
   return builder.append( password.substring( password.length( ) - 1 ) ).toString( );
}

   

change maven local repository path - symbolic links

Let's suppose we want to change the local maven repo path (default : c:\users\user_name\.m2\repository) to some other real folder - lets say e:\repo  - so that the contents from e:\repo folder are mapped to the default folder location.

This might be useful when .m2 folder on your C: drive is taking too much space. In such case, you can move the content to another drive ( e:\repo) and have a symbolic link on C:\ drive instead - so that all the configuration remains intact.


The following command creates a link folder "repository" in /.m2 folder and points to the source e:\REPO

C:\>mklink /d c:\users\gtiwari\.m2\repository e:\REPO


Note:


using symbolic links on windows

Using symbolic links (MKLINK comand) on windows:

Suppose we want to create a link of folder 'e:\source' to c:\target\bridge then, use the following command:

C:\>mklink /d c:\target\bridge e:\source

Syntax : mklink /d TARGET SOURCE_DIR

  • This command creates a link folder "bridge" in c:\target\ where you can see the contents from e:\source.
For more info :
Visit: http://ss64.com/nt/mklink.html - 

Linux find command

The find command is one of the most important and much used command in Linux systems. find command is used to search and locate list of files and directories based on conditions you specify for files that match the arguments. In this article we will get familier with linux find command.

First things first, to get more knowledge on any linux command we can use linux manual page using man <command_name>. For more information about find you can use man find and you'll get in depth description on how we can use linux command.

Basic use of find looks somewhat like below

find .

Let's get familier which the syntax of find. In above example we have two parts

  1. find : find is the command itself
  2. . : . (dot) represents the path from where we want to search. We can pass any path here and find will start to look from the path what was provided.

If you run the command, you will get list of all the files and directories that is inside the path that was given as argument.

But I assume you don't want to search for all files. You may want to search for file from / directories that has specific name. To seach for specific file / directories we can use -name option. Here's an example of find which search for the file / directories with the name .gitignore

find . -name '.gitignore'

# OUTPUT

./.gitignore

You can see that we are using . here. If you wanted to start search from root you are free to pass / as you seach directory.

Did you notice that I kept on saying search for file or directories. By default find will try to match the option of -name on both directories and files. If you want to limit your search for file or directories you can use -type option.

find . -type d -name 'img'

# OUTPUT

./_site/img
./img

If you pass d argument on -type option your search will limit to directories only.

find . -type f -name '.gitignore'

# OUTPUT

./.gitignore

If you pass f argument on -type option your search will limit to files.

Linux system are case sensitive. What if you want to seach file ignoring the case. -iname can be use to do just that.

find . -iname '.gitignore'

You can also search file with certain extention. Let's search file with .css extention

find . -type f -name '*.css'

# OUTPUT
./css/bootstrap-theme.css
./css/pygment_highlights.css
./css/main-minimal.css
./css/bootstrap.css
./css/bootstrap.min.css
./css/normalize.css
./css/bootstrap-theme.min.css
./css/main.css

We can use * to indicate any character. We can also search files with multiple extention. Suppose you want to search file with .css and .html. You can do that with

find . -name '*.css' -or -name '*.html'

# OUTPUT

./_layouts/post.html
./_layouts/default.html
./_layouts/page.html
./_layouts/base.html
./index.html
./css/bootstrap-theme.css
./css/pygment_highlights.css
./css/main-minimal.css
./css/bootstrap.css
./css/bootstrap.min.css
./css/normalize.css
./css/bootstrap-theme.min.css
./css/main.css

Notice how we are joining the option -name in above syntax using -or. -or can be used with its alias -o You may have guessed that we can use -and too. Here's an example of find using -and.

# find . -name 'm*' -name '*.css'
find . -name 'm*' -and -name '*.css'

# OUTPUT
./_site/css/main-minimal.css
./_site/css/main.css
./css/main-minimal.css
./css/main.css

Now that you know about -or and -and, you may have imagined endless possibilities of search patterns. Just a quick note, if you use two -name without -and on above example it would act as -and. Quick hint !! you have -not option too. -not can be used with its alias !. -or , -and and -not can be used with other option too.

You can also control how deep you want to search usign -maxdepth

find . -maxdepth 1 -name '*.html'

# OUTPUT
./index.html

You can use find to search the files / directories based on modified, changed or accessed days and minutes.

For days you have -mtime, -atime, -ctime and for minutes you have -mmin, -amin, -cmin. Option prefixed with m denotes modified, a denotes accessed and c denotes changed.

find . -mtime 20
find . -atime 20
find . -ctime 20
find . -mmin 20
find . -amin 20
find . -cmin 20

We can also use + and - symbol number provied. For example

find . -mtime +5

Above command find the file which was not modified in last 5 days.

find . -mtime -5

Above command find the file which was modified within last 5 days.

You can also go for range of days and minutes. Here's an example

find . -mtime +5 -mtime -10

Above command finds the files / directories that are modifined between 5 to 10 days

find . -mmin +5 -mtime -10

Above command finds the files / directories that are modifined between 5 to 10 minutes.

To search the file that has specific size you can use -size option

find . -type f -size 2M

Above command search file that has exactly 50M. We can also use + and - symbol on the number here. For example

find . -type f -size -2M

This command will find the files that has size of 2MB and less

For range you can do

find . -type f -size +2M -size -10M

To find empty file or directory you can use -empty option

find . -empty

find also has option -user, -group and -perm which lets you search the file that is associated with specific user, group or if the file has certain permission.

You can also perform certain operation on the files / directories that are searched and found using -exec option.

For this example here is the list of files and dir that I have

-rw-rw-r--  1 aman aman    0 Oct  7 10:30 four.html
-rw-rw-r--  1 aman aman    0 Oct  7 10:30 one.txt
drwxrwxr-x  2 aman aman 4096 Oct  7 10:31 somedir
-rw-rw-r--  1 aman aman    0 Oct  7 10:30 three.txt
-rw-rw-r--  1 aman aman    0 Oct  7 10:30 two.php

To rename the two.php to two.html you can issue following command

find . -type f -name 'two.php' -exec mv -f {} two.html \;

# ls -l

-rw-rw-r--  1 aman aman    0 Oct  7 10:30 four.html
-rw-rw-r--  1 aman aman    0 Oct  7 10:30 one.txt
drwxrwxr-x  2 aman aman 4096 Oct  7 10:31 somedir
-rw-rw-r--  1 aman aman    0 Oct  7 10:30 three.txt
-rw-rw-r--  1 aman aman    0 Oct  7 10:30 two.html

Let's explain what -exec is performing. After -exec we are writing the command that we want to execute. In our example we wanted to change two.php to two.html. Notice we are using {} placeholder in source section. To end the -exec command we are using \;.

I know on destination we used static text. What if we want to use change all html files to php now. Here's the command

find . -type f -name '*.html' -exec bash -c 'mv "$1" "${1%.html}".php' - {} \;

Now that's a complex command. Let's me explain what's happening.

First we are passing bash -c '<command_to_execute_inside_bash>' - <param_to_send> on -exec. The command will execute for each entry that is found by find command. If find finds 5 files with *.html it will run the command 5 times.

Lets look at the command that we passed for execution i.e mv "$1" "${1%.html}".php.

$1 is the first argument that was passed to command. For example if we have 2 file with html extention. It will send 1st file found to command as its 1st argument and command execution will take place. Then, it goes for 2nd find found and will again pass the file name as its 1st argument.So if we have two file one.html and two.html our find command will find the one.html first and it will execute our command which argument one.html. So on first execution $1 value will be one.html and on second execution $1 will be two.html

Next we have "${1%.html}".php. In a simple term if $1 represents one.html then "${1%.html}" will represent one. So "${1%.html}".php will represent one.php. Visit Bash Referrence Manural for more detail.

If we have two file one.html and two.html. When our command execute the first time ti will look like bash -c 'mv one.html one.php' and second time bash -c 'mv two.html two.php'.

Here's the output

-rw-rw-r-- 1 aman aman    0 Oct  7 10:30 four.php
-rw-rw-r-- 1 aman aman    0 Oct  7 10:30 one.txt
drwxrwxr-x 2 aman aman 4.0K Oct  7 10:31 somedir
-rw-rw-r-- 1 aman aman    0 Oct  7 10:30 three.txt
-rw-rw-r-- 1 aman aman    0 Oct  7 10:30 two.php
find is very handy command and I hope this article helped you get an insight on how you can use find to search files and directories you need.

Java - OS independent line separator

 You might already knew, the new line character depends on your OS.
  • \n for Unix
  • \r\n for Windows and 
  • \r for old Macs
  • and so on

Always use
System.getProperty("line.separator")
OR
Java 7's way: System.lineSeparator()

This will let you find out OS specific line separator instead of judging yourself and hard coding it. It also helps you in avoiding bugs.

Bonus information:
The new line characters originated from the old type writer era.
  • Carriage return - CR = \r
  • Line feed - LF = \n
Read wikipedia article for more information about new line characters.

Spring Interview Questions Answers - Mostly Asked 2

Spring Interview Questions - 2

Question: What are the pros or benefits of Spring framework ?

The pros of Spring framework are as follows:
  • Spring is an open source framework and free to download.
  • Spring has layered architecture. You can select the feature you wants, you can have Struts MVC and Springs IOC container in one application itself. Eventhough spring has MVC framework if you want you can opt out.
  • Spring Enables Plain Old Java Object (POJO) Programming. POJO programming enables continuous integration and testability.
  • Dependency Injection is really cool stuff, spring 3.0 onwards the introduction of component-scan/autowiring and Spring Expression Language makes it even spicier.
  • spring is lightweight.

Question: What is Dependency Injection/Inversion Of Control(IOC) in Spring framework ?

The basic concept of the Dependency Injection or Inversion of Control is that, programmer do not need to create the objects, instead just describe how it should be created. No need to directly connect your components and services together in program, instead just describe which services are needed by which components in a configuration file/xml file. The Spring IOC container is then responsible for binding it all up.
In other words, while applying Inversion Of Control, at the time of object creation, objects are given their dependencies by some external entity that coordinates each object in the system. That means, dependencies are injected into objects at the time of their creation. So, Inversion of Control means an inversion of responsibility with regard to how an object obtains references to collaborating objects.

Question: What are the different types of Inversion of Control or dependency injection ?

There are three different types of Inversion of Control or dependency injection:
  • Setter Injection: Dependencies are injected through JavaBeans properties (ex: setter/Getter methods in bean objects).
  • Constructor Injection: Dependencies are assigned as constructor parameters.
  • Interface Injection: Injection is done through an interface.

Constructor and Setter Injection are the two dependency injection method which Spring supports.

Question: What are the advantages or Pros of IOC (Dependency Injection) ?

Advantages of Dependency Injection/Inversion of Control are as follows:
  • Dependency Injection minimizes the amount of code in any application. Dependency is handled by the framework itself.
  • Dependency Injection makes developers life easier. With Inversion of Control containers developers do not need to think about how services are created and how to get references to the ones he needs.
  • Easily scalable applications. It’s very easy to add additional services by adding a new constructor or a getter/setter method with a minimal configuration. With Spring Framework 3.0, its even easier as <context:component-scan base-package=”com.blah.blah”/> will do everything for you, you don’t need to add getter and setter method and beans for each dependency injection, just autowire the services wherever it needed.<Read how spring 3.0 made a developers life easier>
  • Dependency Injection makes your application more test-friendly by not demanding any JNDI lookup mechanisms or singletons in your test cases. IOC containers make testing and switching implementations easy by allowing you to inject your own objects into the object under test.
  • Comparing to other options like factory design pattern the IOC container is injecting the dependency into requesting piece of code where as the factory design pattern is more intrusive and components or services need to be requested explicitly.
  • IOC containers support eager instantiation and lazy loading of services.
  • IOC Containers provide support for instantiation of cyclical dependencies, managed objects, life cycles management and dependency resolution between managed objects etc.

Question: What are the difference between BeanFactory and ApplicationContext in spring?


ApplicationContext.

BeanFactory
Here we can have more than one config files possible
In this only one config file or .xml file
Application contexts can publish events to beans that are registered as listeners
Doesn’t support.
Support internationalization (I18N) messages
It’s not
Support application life-cycle events, and validation.
Doesn’t support.
Support  many enterprise services such JNDI access, EJB integration, remoting
Doesn’t support.


Question: What is difference between singleton and prototype bean?

Ans: Basically a bean has scopes which defines their existence on the application

Singleton: means single bean definition to a single object instance per Spring IOC container.
Prototype: means a single bean definition to any number of object instances.
Whatever beans we defined in spring framework are singleton beans. There is an attribute in bean tag named ‘singleton’ if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.
<bean id="createNewStock" class="springexample.stockMarket.CreateNewStockAccont" singleton=”false”
     <property name="newBid"/>
</bean>

Question: What is bean wiring?

Ans: Combining together beans within the Spring container is known as bean wiring or wiring. When wiring beans, you should tell the container what beans are needed and how the container should use dependency injection to tie them together.


Question: What are the important beans lifecycle methods?

Ans: There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.

Question: Explain Bean-LifeCycle.

Ans: Spring framework is based on IOC so we call it as IOC container also. So Spring beans reside inside the IOCcontainer. Spring beans are nothing but Plain old java object (POJO).

Following steps explain their life cycle inside container.
  • Container will look the bean definition inside configuration file (e.g. bean.xml).
  • Using the dependency injection, spring populates all of the properties as specified in the bean definition.
  • If the bean implements the BeanNameAware interface, the factory calls setBeanName() passing the bean’s ID.
  • If the bean implements the BeanFactoryAware interface, the factory calls setBeanFactory(), passing an instance of itself.
  • If there are any BeanPostProcessors associated with the bean, their post- ProcessBeforeInitialization()methods will be called before the properties for the Bean are set.
  • If an init() method is specified for the bean, it will be called.
  • If the Bean class implements the DisposableBean interface, then the method destroy() will be called when the Application no longer needs the bean reference.
  • If the Bean definition in the Configuration file contains a 'destroy-method' attribute, then the corresponding method definition in the Bean class will be called.

Question: How can you override beans default lifecycle methods?

Ans:The bean tag has two more important attributes with which you can define your own custom initialization and destroy methods. Here I have shown a small demonstration. Two new methods fooSetup and fooTeardown are to be added to your Foo class.
<beans>
  <bean id="bar" class="com.act.Foo"
     init-method="fooSetup" destroy="fooTeardown"/>
</beans>

Question: What are Inner Beans?

When wiring beans, if a bean element is embedded to a property tag directly, then that bean is said to the Inner Bean. The drawback of this bean is that it cannot be reused anywhere else.

Question: What is Auto wiring?

You can wire the beans as you wish. But spring framework also does this work for you. It can auto wire the related beans together. All you have to do is just set the autowire attribute of bean tag to an autowire type.



<beans>
     <bean id="bar" class="com.act.Foo" Autowire="autowire type"/>
</beans>

Question: How do add a bean in spring application?








<?xml version="1.0" encoding="UTF-8"?>
  <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
<beans>
   <bean id="foo" class="com.act.Foo"/>
        <bean id="bar" class="com.act.Bar"/
</beans>
In the bean tag the id attribute specifies the bean name and the class attribute specifies the fully qualified class name.

Question: What are different types of Autowire types?

There are four different types by which autowiring can be done.
  • byName
  • byType
  • constructor
  • autodetect

Question: What is an Aspect?

An aspect is the cross-cutting functionality that you are implementing. It is the aspect of your application you are modularizing. An example of an aspect is logging. Logging is something that is required throughout an application. However, because applications tend to be broken down into layers based on functionality, reusing a logging module through inheritance does not make sense. However, you can create a logging aspect and apply it throughout your application using AOP.

Question: What is a Jointpoint?

A joinpoint is a point in the execution of the application where an aspect can be plugged in. This point could be a method being called, an exception being thrown, or even a field being modified. These are the points where your aspect’s code can be inserted into the normal flow of your application to add new behavior.

Question: What is an Advice?

Advice is the implementation of an aspect. It is something like telling your application of a new behavior. Generally, and advice is inserted into an application at joinpoints.

Question:  What is a Pointcut?

A pointcut is something that defines at what joinpoints an advice should be applied. Advices can be applied at any joinpoint that is supported by the AOP framework. These Pointcuts allow you to specify where the advice can be applied.

Question: What is an Introduction in AOP?

An introduction allows the user to add new methods or attributes to an existing class. This can then be introduced to an existing class without having to change the structure of the class, but give them the new behavior and state.


Question: What is a Target?

A target is the class that is being advised. The class can be a third party class or your own class to which you want to add your own custom behavior. By using the concepts of AOP, the target class is free to center on its major concern, unaware to any advice that is being applied.


Question: What is a Proxy?

A proxy is an object that is created after applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

Question: What is meant by Weaving?

The process of applying aspects to a target object to create a new proxy object is called as Weaving. The aspects are woven into the target object at the specified joinpoints.


Question: What are the different points where weaving can be applied?

  • Compile Time
  • Classload Time
  • Runtime

Question: What are the different advice types in spring?

  • Around : Intercepts the calls to the target method
  • Before : This is called before the target method is invoked
  • After : This is called after the target method is returned
  • Throws : This is called when the target method throws and exception
  • Around : org.aopalliance.intercept.MethodInterceptor
  • Before : org.springframework.aop.BeforeAdvice
  • After : org.springframework.aop.AfterReturningAdvice
  • Throws : org.springframework.aop.ThrowsAdvice

 

Question: Explain about PreparedStatementCreator?

Ans: PreparedStatementCreator is one of the most common used interfaces for writing data to database. The interface has one method createPreparedStatement().
1
2
PreparedStatement <strong>createPreparedStatement</strong>
(Connection conn) throws SQLException;
When this interface is implemented, we should create and return a PreparedStatement from the Connection argument, and the exception handling is automatically taken care off. When this interface is implemented, another interface SqlProvider is also implemented which has a method called getSql()which is used to provide sql strings to JdbcTemplate.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path - Solution

Solution to the Java Web Project error : " The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path ".

Add the javax.servlet-api library (servlet.jar) to class path. If you're using maven add the following dependency ( scope = provided, runtime dependency will be provided by the servlet container i.e your web server eg : tomcat, jboss etc)



        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

Hibernate Interview Questions Answers - Most Asked

Hibernate Interview Questions

Q. What are the id generator classes in hibernate?

A:  The optional <generator> child element names a Java class used to generate unique identifiers for instances of the persistent class. If any parameters are required to configure or initialize the generator instance, they are passed using the <param> element.

<id name="id" type="long" column="cat_id">
        <generator class="org.hibernate.id.TableHiLoGenerator">
                <param name="table">uid_table</param>
                <param name="column">next_hi_value_column</param>
        </generator>
</id>
All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:

increment: It generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. It should not the used in the clustered environment.
identity: It supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.
sequence: The sequence generator uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int
hilo: The hilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database. Do not use this generator with connections enlisted with JTA or with a user-supplied connection.
seqhilo: The seqhilo generator uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.
uuid: The uuid generator uses a 128-bit UUID algorithm to generate identifiers of type string, unique within a network (the IP address is used). The UUID is encoded as a string of hexadecimal digits of length 32.
guid: It uses a database-generated GUID string on MS SQL Server and MySQL.
native: It picks identity, sequence or hilo depending upon the capabilities of the underlying database.
assigned: lets the application to assign an identifier to the object before save() is called. This is the default strategy if no <generator> element is specified.
select: retrieves a primary key assigned by a database trigger by selecting the row by some unique key and retrieving the primary key value.
foreign: uses the identifier of another associated object. Usually used in conjunction with a <one-to-one> primary key association. 


Q. How do you define hibernate mapping file in spring?

A. Add the hibernate mapping file entry in mapping resource inside Spring’s applicationContext.xml file in the web/WEB-INF directory.
 

<property name="mappingResources">
    <list>
        <value>org/appfuse/model/User.hbm.xml</value>
    </list>
</property>
 

Q. What are the key benifits of Hibernate?

A:  These are the key benifits of Hibernate:
  • Transparent persistence based on POJOs without byte code processing 
  • Powerful object-oriented hibernate query language
  • Descriptive O/R Mapping through mapping file.
  • Automatic primary key generation 
  • Hibernate cache : Session Level, Query and Second level cache.
  • Performance: Lazy initialization, Outer join fetching, Batch fetching

Q. What is hibernate session and session factory? How do you configure sessionfactory in spring configuration file?

A. Hibernate Session is the main runtime interface between a Java application and Hibernate. SessionFactory allows applications to create hibernate session by reading hibernate configurations file hibernate.cfg.xml.
 

// Initialize the Hibernate environment
Configuration cfg = new Configuration().configure();
// Create the session factory
SessionFactory factory = cfg.buildSessionFactory();
// Obtain the new session object
Session session = factory.openSession();
 
The call to Configuration().configure() loads the hibernate.cfg.xml configuration file and initializes the Hibernate environment. Once the configuration is initialized, you can make any additional modifications you desire programmatically. However, you must make these modifications prior to creating the SessionFactory instance. An instance of SessionFactory is typically created once and used to create all sessions related to a given context.
The main function of the Session is to offer create, read and delete operations for instances of mapped entity classes. Instances may exist in one of three states:


transient: never persistent, not associated with any Session
persistent: associated with a unique Session
detached: previously persistent, not associated with any Session
A Hibernate Session object represents a single unit-of-work for a given data store and is opened by a SessionFactory instance. You must close Sessions when all work for a transaction is completed. The following illustrates a typical Hibernate session:
Session session = null;
UserInfo user = null;
Transaction tx = null;
try {
   session = factory.openSession();
   tx = session.beginTransaction();
   user = (UserInfo)session.load(UserInfo.class, id);
   tx.commit();
} catch(Exception e) {
   if (tx != null) {
      try {
         tx.rollback();
      } catch (HibernateException e1) {
         throw new DAOException(e1.toString()); }
   } throw new DAOException(e.toString());
} finally {
   if (session != null) {
      try {
         session.close();
      } catch (HibernateException e) { }
   }
}


Q. What is the difference between hibernate get and load methods?

A. The load() method is older; get() was added to Hibernate’s API due to user request. The difference is trivial:
The following Hibernate code snippet retrieves a User object from the database:  User user = (User) session.get(User.class, userID);
The get() method is special because the identifier uniquely identifies a single instance of a class. Hence it’s common for applications to use the identifier as a convenient handle to a persistent object. Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached.
Hibernate also provides a load() method:  User user = (User) session.load(User.class, userID);
If load() can’t find the object in the cache or database, an exception is thrown. The load() method never returns null. The get() method returns
null if the object can’t be found. The load() method may return a proxy instead of a real persistent instance. A proxy is a placeholder instance of a runtime-generated subclass (through cglib or Javassist) of a mapped persistent class, it can initialize itself if any method is called that is not the mapped database identifier getter-method. On the other hand, get() never returns a proxy. Choosing between get() and load() is easy: If you’re certain the persistent object exists, and nonexistence would be considered exceptional, load() is a good option. If you aren’t certain there is a persistent instance with the given
identifier, use get() and test the return value to see if it’s null. Using load() has a further implication: The application may retrieve a valid reference (a proxy) to a persistent instance without hitting the database to retrieve its persistent state. So load() might not throw an exception when it doesn’t find the persistent object in the cache or database; the exception would be thrown later, when the proxy is accessed. 


Q. What type of transaction management is supported in hibernate? 

A. Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions.
    non-managed in web containers:
 

<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
    <property name="sessionFactory">
        <ref local="sessionFactory"/>
    </property>
</bean>
 
    managed in application server using JTA:
 

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager.">
    <property name="sessionFactory">
        <ref local="sessionFactory"/>
    </property>
</bean>
 

Q. What is lazy loading and how do you achieve that in hibernate?

A. Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database. Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.
Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.


Q. What are the different fetching strategy in Hibernate?


A. Hibernate3 defines the following fetching strategies:
 
Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using an OUTER JOIN. 
Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.
Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will only be executed when you actually access the association.Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.

Q. What are different types of cache hibernate supports ?

A. Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects: first-level cache and second-level cache
First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided. In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box: 
  • EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
  • OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
  • SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
  • JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.

Q. What are the different caching strategies?

A. The following four caching strategies are available:
  • Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
  • Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
  • Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
  • Transactional: This is a fully transactional cache that may be used only in a JTA environment.

Q. How do you configure 2nd level cach in hibernate?

A. To activate second-level caching, you need to define the hibernate.cache.provider_class property in the hibernate.cfg.xml file as follows: 
<hibernate-configuration>
    <session-factory>
        <property name="hibernate.cache.provider_class">org.hibernate.cache.EHCacheProvider</property>
    </session-factory>
</hibernate-configuration>
By default, the second-level cache is activated and uses the EHCache provider.
To use the query cache you must first enable it by setting the property hibernate.cache.use_query_cache to true in hibernate.properties.


Q. What is the difference between sorted and ordered collection in hibernate?

A. A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.

Q. What are the types of inheritence models and describe how they work like vertical inheritence and horizontal?

A. There are three types of inheritance mapping in hibernate :
Example: Let us take the simple example of 3 java classes. Class Manager and Worker are inherited from Employee Abstract class.
1. Table per concrete class with unions : In this case there will be 2 tables. Tables: Manager, Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be only one table in database called 'Employee' that will represent all the attributes required for all 3 classes. But it needs some discriminating column to differentiate between Manager and worker;
3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and Worker