Java Login

About javalogin.com

Hello guys,
javalogin.com is for Java and J2EE developers, all examples are simple and easy to understand 

It is developed and maintained by Vaibhav Sharma. The views expressed on this website are his own and do not necessarily reflect the views of his former, current or future employers. I am professional Web development. I work for an IT company as Senior Consultant. Primary I write about spring, hibernate and web-services. I am trying to present here new technologies.


     << Previous


Hibernate Interview Question

Q.Why do you need ORM tools like hibernate?
Ans. The main advantage of ORM like hibernate is that it shields developer 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



Q.Define cascade and inverse option in one-many mapping?
Ans. What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:- An implicit association joins An ordinary join in the FROM clause A fetch join in the FROM clause. A theta-style join in the WHERE clause.



Q. Difference between get and load in Hibernate?
Ans. load() vs. get() method : load()

  • 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
  • load() just returns a proxy by default and database won't be hit until the proxy is first invoked.

get()

  • 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.
  • get() will hit the database immediately.


Q. Difference between save, persist and saveOrUpdate methods in Hibernate?
Ans. save and persist :The save and persist methods are used to persist the transient instance. Save and persist method results a sql insert query. If any properties are updated after the save or persist method and before the transaction is committed or session is flushed, the changes will be saved to the database using update query.
public Serializable save(Object object) throws HibernateException
public void persist(Object object) throws HibernateException

  • The return type of the save method is java.io.Serializable it returns the generated identity value whereas the return type of persist method is void it does not return anything. 
  • Persist method can be used only within the boundary of a transaction whereas save method can be used inside or outside the transaction boundaries 
  • Save method assigns the generated identifier immediately whereas persist method does not guarantee the assignment immediately it may assign at flush time. 
  • Save method take comparatively more time to execute than persist method.

session.saveOrUpdate() : saveOrUpdate does a select first to determine if it needs to do an insert or an update. Insert data if primary key not exist otherwise update data.



Q. What is bi-directional and uni-directional relationship between entities and how do you mention it in your classes ?
Ans. Both bi-directional and uni-directional is a technquie used to locate related row of entity given. If we can get the related row of one entity for the given entity only in one direction then it is called uni-directional, But if we can locate a related entity for a given row in both the direction then it is called bi-directional. These relationship helps us to locate an item with easy. For example if we have two entities related in bi-directional then we can save any entity to the database ( since they are related , both of the entity will be saved) , and we can retrive the other entity we did not save ( in coding wise ) and retrive the saved entity. For example take that X and Y entities are related in bi-directional way , then we can do like session.save(xRef); and retrive session.get(Y.class,1) , which gives us the Y entity , but by using yRef.getX() we can retrive the X.



Q. What is the main difference between Entity Beans and Hibernate ?
Ans. The main difference between Entity Beans and Hibernate :

  • In Entity Bean at a time we can interact with only one data Base. Where as in Hibernate we can able to establishes the connections to more than One Data Base. Only thing we need to write one more configuration file. 
  • EJB need container like Weblogic, WebSphare but hibernate don't nned. It can be run on tomcat.  
  • Entity Beans does not support OOPS concepts where as Hibernate does.  
  • Hibernate supports multi level cacheing, where as Entity Beans doesn't.  
  • In Hibernate C3P0 can be used as a connection pool.  
  • Hibernate is container independent. EJB not. 


Q. What is Hibernate proxy?
Ans. By default Hibernate creates a proxy for each of the class you map in mapping file. This class contain the code to invoke JDBC. This class is created by hibernate using CGLIB.
Proxies are created dynamically by subclassing your object at runtime. The subclass has all the methods of the parent, and when any of the methods are accessed, the proxy loads up the real object from the DB and calls the method for you. Very nice in simple cases with no object hierarchy. Typecasting and instanceof work perfectly on the proxy in this case since it is a direct subclass.



Q. Difference between session.update() and session.lock() in Hibernate ?
Ans. Both of these methods and saveOrUpdate() method are intended for re-attaching a detached object. The session.lock() method simply re-attaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
Each interaction with the persistent store occurs in a new Session. However, the same persistent instances are reused for each interaction with the database. The application manipulates the state of detached instances originally loaded in another Session and then "re-associates" them using Session.update() or Session.saveOrUpdate().

// foo is an instance loaded by a previous Session
foo.setProperty("bar");
session = factory.openSession();
session.saveOrUpdate(foo);
session.flush();
session.connection().commit();
session.close();

You may also call lock() instead of update() and use LockMode.READ (performing a version check, bypassing all caches) if you are sure that the object has not been modified.



Q. What are the Instance states in Hibernate?
Ans. There are three instance state exists in Hibernate:
transient The instance is not, and has never been associated with any persistence context. It has no persistent identity (primary key value).
persistent The instance is currently associated with a persistence context. It has a persistent identity (primary key value) and, perhaps, a corresponding row in the database. For a particular persistence context, Hibernate guarantees that persistent identity is equivalent to Java identity (in-memory location of the object).
detached The instance was once associated with a persistence context, but that context was closed, or the instance was serialized to another process. It has a persistent identity and, perhaps, a corrsponding row in the database. For detached instances, Hibernate makes no guarantees about the relationship between persistent identity and Java identity.



Q. Difference between getCurrentSession() and openSession() in Hibernate ?
Ans. Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don?t need to close it. Once the session factory is closed, this session object gets closed.
Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.



Q. What is Hibernate?
Ans. Hibernate is a free, open source Java package that makes it easy to work with relational databases. Hibernate makes it seem as if your database contains plain Java objects like you use every day, without having to worry about how to get them out of (or back into) mysterious database tables. It liberates you to focus on the objects and features of your application, without having to worry about how to store them or find them later.
This includes providing data query and retrieval facilities, with the ability to generate SQL calls and prevent developers from having to manually handle and object convert the result set.
The user creates an XML "mapping document" telling Hibernate the classes they want to store in a database, specifying how these relate to the tables and columns in that database.



Q.What is ORM?
Ans. The term object/relational mapping (ORM) refers to the technique of mapping a data representation from an object model to a relational data model with a SQL-based schema. So, what can an ORM do for you? A ORM basically intends to takes most of that burden of your shoulder. With a good ORM, you have to define the way you map your classes to tables once; which property maps to which column, which class to which table, and so forth.
With a good ORM, you can take the plain Java objects you use in the application and tell the ORM to persist them. This will automatically generate all the SQL needed to store the object. An ORM allows you to load your objects just as easily: A good ORM will feature a query language too. The main features include:

  • Less error-prone code  
  • Optimized performance all the time  
  • Solves portability issues  
  • Reduce development time  

Hibernate sounds like the best solution. It allows us to store the data in constant storehouse without serious consequences, thus a choice of such as storehouse, installation, and configuration do not make big difficulties. Hibernate allows us to store objects of any kind; therefore, it is not necessary for an application to know that its data will be kept with Hibernate. Clearly, with help of Hibernate we can not only keep the data in a storehouse, but also update and delete the data.



Q.Explain hibernate architecture?
Ans. The below diagram shows a high-level view of Hibernate architecture.

Hibernate archirtecture has following components:
Configuration: The org.hibernate.cfg.Configuration object reads the configuration files to connect database. SessionFactory object is creaated used Configuration object.
SessionFactory: The SessionFactory is thread-safe as it is created one per database and can be concurrently accessed by multiple threads and is created at the time of application startup. It is created using Configuration object. It is used to create session object.
Session: The org.hibernate.Session is used to create object that are used to communicate between application and persistent store(database). This is factory for org.hibernate.Transaction. As it is not thread-safe, application should create and destroy it once a unit of work done though it may be used to multiple units as per requirement.
Transaction: The org.hibernate.Transaction is used to represent unit of work. A transaction is associated with a session and is usually instiantiated by a call to Session.beginTransaction()
Query: The org.hibernate.Query is an object oriented representation of Hibernate query. A query instance is obtained by calling session.createQuery(). A query object is used to bind query parameters like number of results fetched etc.
Criteria: The org.hibernate.Criteria is used to retrieve entities by composing some criteria like getting all users by specific age or specific weight etc. The Session is factory for Criteria.



Q.What is the general flow of hibernate communication with RDBMS?
Ans. The general flow of Hibernate communication with RDBMS is :

  • Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files  
  • Create session factory from configuration object  
  • Get one session from this session factory  
  • Create HQL Query  
  • Execute query to get list containing Java objects  


Q.What is EntityManager?
Ans. SessionFactory and Session are hibernate-specific. The EntityManager invokes the hibernate session under the hood. And if you need some specific features that are not available in the EntityManager, you can obtain the session by calling:

Session session = entityManager.unwrap(Session.class);

If you're talking about Hibernate, then the EntityManager and the Hibernate Session are equivalent. You use the EntityManager if you want to use the Java Persistence API, and Hibernate's Session if you're using Hibernate's API.



Q.What are the key benifits of Hibernate?
Ans. Here is a thing in simplest words & explanation:-

  • Hibernate is database independent. You can work with any database you want like oracle,mysql,db2,sql server ,etc. Using hibernate you won't worry about writing database specific queries and syntax. It's provides HQL (Hibernate Query Language), which is compatible with any database server.  
  • In ORM, you will map a database table with java object called "Entity". So once you map these,you will get advantages of OOP concepts like inheritance, encapsulation,etc.  
  • Caching mechanism (1st level & 2nd level cache) provided hibernate means you don't need to hit database for similar queries, you can cache it and use it from buffered memory to improve performance.  
  • Supports Lazy loading (also called n+1 problem in Hibernate). Take an example-parent class has n number of child class. So When you want information from only 1 child class,there is no meaning of loading n child classes.This is called lazy loading (Load only thing which you want).  
  • Hibernate has capability to generate primary keys automatically while we are storing the records into database  
  • This will also supports collections like List,Set,Map (Only new collections)  
  • Hibernate supports relationships like One-To-One, One-To-Many, Many-To-One, Many-To-Many  
  • Hibernate supports annotations, apart from XML  
  • Getting pagination in hibernate is quite simple.  
  • Hibernate supports Inheritance, Associations, Collections  
  • Hibernate provided Dialect classes, so we no need to write sql queries in hibernate, instead we use the methods provided by that API.  


Q.What is lazy loading and how do you implement it in hibernate?
Ans. Lazy fetching decides whether to load child objects while loading the Parent Object. You need to do this setting respective hibernate mapping file of the parent class. Lazy = true (means not to load child) By default the lazy loading of the child objects is true.
The default behavior is to load 'property values eagerly' and to load 'collections lazily'. Contrary to what you might remember if you have used plain Hibernate 2 (mapping files) before, where all references (including collections) are loaded eagerly by default.
Also note that @OneToMany and @ManyToMany associations are defaulted to LAZY loading; and @OneToOne and @ManyToOne are defaulted to EAGER loading. For more information click here



Q.What is the usage of callback interfaces in hibernate?
Ans. Callback interfaces are useful as it allows the application to receive important notification about the objects that are in execution phase. It includes the objects that are loaded, saved or deleted from the Hibernate. It allows the programmer to get the error information or exception handling can be done in a better way to notify the user on run time in case of any problem in the programming code.



Q.What are different ways to enable hibernate second level cache?
Ans. The second level cache is responsible for caching objects across sessions. When this is turned on, objects will first be searched in the session if it not found then delegates searching in the cache and if they are not found, a database query will be fired. Second level cache will be used when the objects are loaded using their primary key. This includes fetching of associations. Second level cache objects are constructed and reside in different memory locations.
The javax.persistence.Cache interface of the persistence provider can be used to interact with the second level cache. This interface provides functions such as, contains: to check whether the cache contains a given (as parameter) entity, variation of evict: to remove a particular entity from the cache, evictAll: to clear the cache and unwrap: to return specified cache implementation by the provider (ref. Javadoc JPA API). We can use @Cacheable annotation to make a POJO eligible to be cached. In this way the persistence provider knows which entity is to be cached. If no such annotation is supplied then entity and its state is not cached by the provider. @Cacheable takes a parameter of boolean value, default is true.
To enable second level cache in the hibernate, then the following 3 changes are required
STEP 1: Add provider classin hibernate configuration file like -

<property name="hibernate.cache.provider_class" > org.hibernate.cache.EhCacheProvider
<property>

STEP 2: Configure cache element for a class in hibernate mapping file -

<cache usage="read-only" />

Note: this must write soon after <class>

STEP 3: create xml file called ehcache.xml and store in at class path location [ no confusions, i mean in the place where you have mapping and configuration XML's in web application.
For more detail click here



Q.What are the benefits of second level cache in Hibernate?
Ans. The second level cache provides benefits in Hibernate.

  • Cache lives outside your application: This helps to keep cache and applications machine separate ensuring consistent access across multiple servers. There are no Data integrity issue as cache data is sharable between all the applications.  
  • Scalable cache architecture: You can add new servers on the fly in a production environment. Architecture distributes data at runtime to accommodate more traffic on high loads.  
  • High availability & Linear Scalability: Scaling out helps to keep data available at times of server failure. The performance gained from adding server is linear, meaning; the more the servers you add the more the performance guaranteed and reducing your database traffic by 80%. Handle higher transactions without worrying about the database bottleneck.  
  • In-process client caches: You can have keep this cache within your application process (InProc mode) or in a local but separate process. All of this gives you a super fast cache very close to your application that boosts your application performance greatly.  
  • Easy Management: Use simple and easy to learn  



Q.What are different types of caches available in Hibernate?
Ans. Hibernate has three caching mechanisms:

  • First level cache  
  • Second level cache  
  • Query cache  


Q.What Query Cache in Hibernate?
Ans.

  • It is used to cache the results of a query  
  • The results of the query are stored against the combination query and parameters. Every time the query is fired, the cache manager checks for the combination of parameters and query. If the results are found in the cache, they are returned; otherwise a database transaction is initiated.
    => It is not a good idea to cache a query if it has a number of parameters, because then a single parameter can take a number of values. For each of these combinations the results are stored in the memory. This can lead to extensive memory usage.  
  • The query cache works something like this:  
["from Employee as e where e.employee.id=? and e.firstName=?", [ 1 , "Adam"] ] -> [ 2 ]
  • The query cache does not cache the state of the actual entities in the cache; it caches only identifier values and results of value type. For this reason, the query cache should always be used in conjunction with the second-level cache for those entities expected to be cached as part of a query result cache. 
  • Most queries do not benefit from caching or their results. So by default, individual queries are not cached even after enabling query caching. To enable results caching for a particular query, call setCacheable(true) on our Query or Criteria object.  
  • It is not enabled by default. To enable it, set in your persistence.xml:  
<property name= "hibernate.cache.use_query_cache">true</property


Q.What is dirty checking in hibernate?
Ans. Dirty Checking is one of the features of hibernate. In dirty checking, hibernate automatically detects whether an object is modified (or) not and need to be updated. As long as the object is in persistent state i.e., bound to a particular Session(org.hibernate.Session). Hibernate monitors any changes to the objects and executes sql.
Note:- For dirty checking to work, the object must exist in cache.
Dirty checking allows the user or developer to avoid the time consuming databases write actions. This feature makes necessary updations and changes to the fields which require a change, remaining fields are left unchanged or untouched. If user commit object into database after that he change the object state, in this case object will be reflect into database automatically



Q.Types of inheritance in Hibernate?
Ans. There are three inheritance mapping strategies defined in the hibernate:

  • Table Per Hierarchy  
  • Table Per Concrete class  
  • Table Per Subclass  


Q.What is difference between sorted collection and ordered collection? Which one is better?
Ans. Sorted collection is the way of sorting a collection by leveraging the sorting features provided by the Java collections framework. This sorting uses Java comparator and it takes place in the memory of JVM in which Hibernate is running, once the data being read from database. If your collection is not large, it will be more efficient way to sort it.

Ordered collection refers to the sorting of a collection by specifying the order-by clause when retrieval.

Ordered collection is preferred for larger data set whereas if the collection is considerably small, sorted collection is preferred. Smaller the collection lesser impact on the JVM memory.



Q.What are the various collection types in hibernate?
Ans. Hibernate permits collection mapping as value type. The collection are mapped into a separate table but are not disclosed as entity on the Java side in the hibernate collection mapping and it supports the following interfaces.There are examples listed here on collection mapping.

  • java.util.Set - java.util.HashSet is used to store value.  
  • java.util.SortedSet - java.util.TreeSet is used to store value.  
  • java.util.List - java.util.ArrayList is used to store value. Preserves the position with an index column  
  • Bag semantics - java.util.ArrayList is used to store value however the position is not preserved.  
  • java.util.Map - java.util.HashMap is used to store value.  
  • java.util.SortedMap - java.util.TreeMap is used to store value.  

Q.What is Named SQL Query?
Ans. Hibernate Named Query can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery. Named query is the static query expressed in metadata.Query names are scoped to persistence unit. The following is an example of the definition of a named query

@NamedQuery(
name="findAllEmployeesWithName",
query="SELECT e FROM Employee e WHERE e.name LIKE :empName"
)

For more information click here



Q.Why should we use hibernate criteria API? OR, What are the benefits of Criteria API?
Ans. In Hibernate, the Criteria API helps us build criteria query objects dynamically. Criteria is a another technique of data retrieval apart from HQL and native SQL queries. The primary advantage of the Criteria API is that it is intuitively designed to manipulate data without using any hard-coded SQL statements. Programmatic behavior offers compile-time syntax checking; as a result, most error messages are delivered during compilation. Although it's convenient, this does not provide any performance enhancing ability over HQL or native SQL queries. it is very important as it helps to query database where you can apply filteration rules and logical conditions programatically on object using methods provided by Criteria API.
For example: If you want to query User table having salary greater than 1000 the criteria query will be built as:

Criteria cr = session.createCriteria(User.class);
cr.add(Restrictions.gt("salary", 1000));
List results = cr.list();

Similarly, If you want to query User table having salary equal to 1000 the criteria query will be built as:

Criteria cr = session.createCriteria(User.class);
cr.add(Restrictions.eq("salary", 1000));
List results = cr.list();

     << Previous