Hibernate Interview questions Part2

Posted by Zafar Ullah - zafarjcp@gmail.com | 5:40 AM | , , , , , | 0 comments »








16.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.






17.What is the difference
between and merge and update ?



Use
update()
if you are sure that the session does not contain an already
persistent instance with the same identifier, and


merge()

if you want to merge your modifications at any time without consideration of the
state of the session.



19.Define cascade and inverse
option in one-many mapping?



cascade - enable operations to cascade to child entities.

cascade="allnonesave-updatedeleteall-delete-orphan"



inverse - mark this collection as the "inverse" end of a bidirectional
association.

inverse="truefalse"

Essentially "inverse" indicates which end of a relationship should be ignored,
so when persisting a parent who has a collection of children, should you ask the
parent for its list of children, or ask the children who the parents are?



20.What does it mean to be inverse?



It informs hibernate to ignore that end of the relationship. If the one–to–many
was marked as inverse, hibernate would create a child–>parent relationship (child.getParent).
If the one–to–many was marked as non–inverse then a child–>parent relationship
would be created.



23.Explain Criteria API



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.

Example :


List employees = session.createCriteria(Employee.class)

.add(Restrictions.like(
"name", "a%") )

.add(Restrictions.like(
"address", "Boston"))

.addOrder(Order.asc(
"name") )

.list();




24.Define HibernateTemplate?





org.springframework.orm.hibernate.HibernateTemplate

is a helper class which provides different methods for querying/retrieving data
from the database. It also converts checked HibernateExceptions into unchecked
DataAccessExceptions.





25.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.



26.How do you switch between
relational databases without code changes?



Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate
appropriate hql queries based on the dialect defined.



27.If you want to see the Hibernate generated SQL statements on console, what
should we do?



In Hibernate configuration file set as follows:

true




28.What are derived properties?



The properties that are not mapped to a column, but calculated at runtime by
evaluation of an expression are called derived properties. The expression can be
defined using the formula attribute of the element.



29.What is component mapping in
Hibernate?




  • A component is an object saved as a value,
    not as a reference


  • A component can be saved directly without
    needing to declare interfaces or identifier properties


  • Required to define an empty constructor


  • Shared references not supported



Example
:



























30.What is the difference
between sorted and ordered collection in hibernate?
sorted collection
vs. order collection
:-


















sorted collection



order collection



A sorted collection is
sorting a collection by utilizing the sorting features provided by the
Java collections framework. The sorting occurs in the memory of JVM which
running Hibernate, after the data being read from database using java
comparator.



Order collection is
sorting a collection by specifying the order-by clause for sorting this
collection when retrieval.



If your collection is not
large, it will be more efficient way to sort it.



If your collection is very
large, it will be more efficient way to sort it .



Hibernate Interview questions Part 1

Posted by Zafar Ullah - zafarjcp@gmail.com | 5:37 AM | , , , , , | 0 comments »

1.What is ORM ?

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What does ORM consists of ?

An ORM solution consists of the followig four pieces:

* API for performing basic CRUD operations
* API to express ries refering to classes
* Facilities to specify metadata
* Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ?

The ORM levels are:

* Pure relational (stored procedure.)
* Light objects mapping (JDBC)
* Medium object mapping
* Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate?

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

5.Why do you need ORM tools like hibernate?

The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

* Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
* Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
* Improved maintainability
o A lot less code to write
* Improved portability
o ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify?

Hibernate simplifies:

* Saving and retrieving your domain objects
* Making database column and table name changes
* Centralizing pre save and post retrieve logic
* Complex joins for retrieving related items
* Schema creation from object model
7.What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:



8.What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:

Programmatic configuration
XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml?
An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.



10.What are the Core interfaces are of Hibernate framework?

The five core interfaces are used in just about every Hibernate application. Using these interfaces, you can store and retrieve persistent objects and control transactions.

* Session interface
* SessionFactory interface
* Configuration interface
* Transaction interface
* Query and Criteria interfaces
11.What role does the Session interface play in Hibernate?

The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.

Session session = sessionFactory.openSession();

Session interface role:

* Wraps a JDBC connection
* Factory for Transaction
* Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier


12.What role does the SessionFactory interface play in Hibernate?

The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole application—created during application initialization. The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work

SessionFactory sessionFactory = configuration.buildSessionFactory();

13.What is the general flow of Hibernate communication with RDBMS?

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


14.What is Hibernate Query Language (HQL)?

Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

15.How do you map Java Objects with Database tables?

* First we need to write Java domain objects (beans with setter and getter). The variables should be same as database columns.
* Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example :



name="userName" not-null="true" type="java.lang.String"/>
name="userPassword" not-null="true" type="java.lang.String"/>

NHibernate: Unexpected row count: 0; expected: 1

Posted by Zafar Ullah - zafarjcp@gmail.com | 6:32 AM | , , , , | 0 comments »

here are some of my experiences when "Unexpected row count: 0; expected: 1" comes and also how can we solve them.

1. If primarykey generator has some issue e.g you in class its identity and in db its not an identity column. For those columns where your db column is not identity and its part of a requirment then "hilo" works :) for details on generator clickhere

2. Nhibernate seems to have problems when you create multiple transient entities that reference each other, and then try to save just the root entity. To avoid these problems, call
session.Save() on each transient entity after you create it, before you attach it to others else
use session.Update().

I ran into this issue today when trying to persist one of my objects. The cause of the problem was interesting. I was trying to save an object when a property/columns in the table had a unique constraint. As a result, the object that I was trying to persist would not persist simply because the object's property it failed to meet the unique constraint.

As a result, a call to Save() on the object failed and the ID on the object I was trying to save was not set, but NHibernate still processed the object and associated it with its persistence mechanism leaving it in a "semi-persistent" state with the NHibernate persistence manager (ie: NHibernate now knows about the object you tried to save and it SHOULD have fully evicted the object from its persistence manager because the save failed, but it didn't).

When an HTTP request finishes on my ASP.NET application, I flush and close all NHibernate session objects at the time the request is done. And as a result, when the HTTP request finished, NHibernate attempted to flush the jacked up "semi-persistent" object (an object who's ID was null) and ultimately generating the error above.

So, the solution that I implemented was to wrap the Save() in a try{} catch{} statement, and if the save failed, immediately close and shutdown the session, handle the error/exception. Then, check if Session.IsOpen when the HTTP request finishes.

How Hibernate / NHibernate Cascade attribute work

Posted by Zafar Ullah - zafarjcp@gmail.com | 12:57 AM | , , , , , | 0 comments »

Concept 1: when ever you have a set/bag/collection of child in parent class then its attributes must be inverse = true and cascade = "all-delete-orphan".

Concept 2: In above given senario In child class the reference of ParentID should be NotNull=true and if child creates a manytoone relation with parent then its cascade=none because on child deletion or update parent should not be updated.

Concept 3: If parent have no set/bag/collection of child then in child the parent will be NotNull=false means that it can be null. This senario is required if you mark foreignkeys in child table as allow null = true. where as if you mark foreignkeys as Not null in database then its property should be NotNull=true so that child record should not be saved if its parent's foreign key contains null.

Concept 4: if your foreignkey column in database allow null and due to any constraint you dont want to change db columns and you still want that Hibernate/Nhibernate will not save the record if user didnt provide its value then 2 things need to be done.

  • Validate from frontend that the foreign key value must be given
  • In your mapping file in child class mark parent field as NotNull=true. This will enforce that value should be given to this column before save/update.

    Please comment if i am wrong