Hibernate Interview Questions – Part 4

Hibernate Interview Questions – Part 4

Hibernate Interview Questions (Part 1 – Part 2Part 3)

HQL – Hibernate Query Language:

Why HQL?
Most of the applications use Databases like Oracle, SQL etc. So when writing an application we use specific queries to access database. SQL Query might be different when compared with Oracle Query to access databases. So if database with which the application works changes, We need to change the queries accordingly to access the database. To overcome this we use HQL.

In hibernate we use,
Query query = session.createQuery();

Commonly used class in HQL:
Query query = session.createQuery(FROM entityname);

Query query = session.createQuery(SELECT empid from Employee);

Query query = session.createQuery(FROM employee WHERE empname = ’employeename’);

How to Bind Parameters in Query?
We can bind parameters in HQL,
Query query = session.createQuery(“FROM employee WHERE ename= :ename”);
Now we have to pass value to that parameter,
String ename = “Alpha”;
query.setString(“ename”,ename); (for integers its query.setInteger)

How to use Iterator?
Query query = session.createQuery(“FROM employee”);
for(Iterator itr = query.iterate(); itr.hasNext(); ;){
Employee emp = (Employee) itr.next();

How can we use Native SQL Query in Hibernate?
SQLQuery Session.createSQLQuery(String queryString);

Criteria Queries:
Criteria Queries are used to check multiple conditions and add restrictions in a query.
To create Criteria Queries,
Criteria createCriteria

Adding Restrictions in a Query
Criteria criteria = session.createCriteria(Employee.class);
criteria.add(Restrictions.eq(“columnname”, “condition”));

Criteria Queries with Restrictions:

.add(Restrictions.eq(Propertyname, object value) – This will compare the property name equals to the object value

.add(Restrictions.gt(Propertyname, object value) – This will return the results when the value of that property is greater than the specified value

.add(Restrictions.lt(Propertyname, object value) – This will return the results when the value of that property is lesser than the specified value

.add(Restrictions.ge(Propertyname, object value) – This will return the results when the value of that property is greater than or equal to the specified value

.add(Restrictions.le(Propertyname, object value) – This will return the results when the value of that property is lesser than or equal to the specified value

.add(Restrictions.like(Propertyname, object value) – This will compare the propertywith specified pattern

.add(Restrictions.between(Propertyname, object low, object high) – This method compares the property within the range of low and high




Read More

Hibernate Interview Questions – Part 3

Hibernate Interview Questions – Part 3

Hibernate Interview Questions – Part 1Part 2

Explain One – to – One Mapping:
Consider we have 2 tables, Employee and Employee Address. We save the employee details at one table like his name, employee number etc and we save employee address in another table. We will have a one to one relationship for specific employee from employee table to specific records in Employee Address table.

Consider there is an employee named Alpha in Employee table and let the primary key for Alpha be 1. Now the table Employee will have an column that links to Employee Address table and that Employee Address will point to a record in Employee Address table.

Detailed Explanation Here

Explain OneToMany Mapping:
Consider an employee might have more than one address, So as OnetoMany mapping points out, A single employee can have more than one address in another table. (Detail Here)

Explain ManytoMany Mapping:
let us consider 2 entities – Employee and Address. An employee can have more than one address let us assume permanent and temporary address, Same way more than one employee would have stayed in the temporary address. This scenario shows Employee can have more than one address and an address can have more than one employee. This is ManyToMany mapping. (Details Here)

Explain Table per Concrete Class:
In this method, a table is created for each class in the inheritance. Each table will have its own property columns and also has its base class properties. We will have repeated columns of base class in all sub classes

Explain Table per Class:
In this method, a single table is created for all classes both Base and Subclass. We have to define a column Discriminator column to differentiate object of base and subclass.(Detailed Explanation Here)

Explain Table per Subclass:
This method, creates a table for each subclass. The difference between table per concrete class and Table per subclass is the Inherited tables will not create columns of base class. It uses foreign key and points to base class for base class properties(Detailed Explanation Here)


Read More

Hibernate Interview Questions – Part 2

Hibernate Interview Questions – Part 2
(Please check here for Hibernate Interview Questions Part -1)

How can you map Beans with Database?
Using XML
Using Annotations

Explain Mapping with XML File:
Specifies the type of XML and the name of Document Type Definition(DTD) contains rule to validate elements

Root of mapping elements

Refers to Java class mapped with database
– class name
– name of database table to which class to be mapped
mutable – If objects in java class are read-only

Primary key column of database.
– property of java class mapped to primary key column of database
type – hibernate type used to map property of java class with primary key column of database
column – specifies primary key column of database.

Generates unique identifiers.
Lets the application assign an identifier to the object before it gets saved in database
Generates unique identifiers for objects stored in database (int, long, short types)
Automatic generation of values in primary key columns. (supports various databases like db2, oracle etc)
Automatic generation of unique identifiers in a sequence
Automatic generation of unique identifiers using identity or sequence depending on database

Maps properties of Java class with database columns
name – specifies name of property in java class to map column in database
type –  specifies type of property in java class to map column in database
column – name of the column in database
length – length of characters for a column

Specifies the column that is to be mapped with database
name – name of the column in database
length – length of characters for that column

Explain mapping using Annotations:
– specify the java class as entity bean

@Table – name of the table

@Column – name of the column
name – name of the column
length – length of the column
unique – contains unique values
nullable – column cannot be null

@Id – primary key

@GeneratedValue – primary key generation strategy
AUTO – Generates primary for each new entity object.
IDENTITY – Similar to AUTO except it is unique only per type Hierarchy
SEQUENCE – Generates ID using defined sequence number(maintains the next sequence number to be used)
TABLE – Similar to sequence, except this stores the last sequence number that’s been used.

Explain Mapping Collections:
Commonly used Mapping collections are List, Set and Bag.
List – Contains duplicate items and implicit ordering of elements
Set – does not contain duplicate items
Bag – Contains duplicates but is not indexed

What is Cascade?
cascade Attribute:
Specifies operations performed in an entity and related entities too.

none: Changes made only in that entity and not to related entities
save-update: Save and Update changes are done in specific entity and all related entities too.
delete:  Delete operation performed in specific entity and related entities.
all: Changes made by save, delete, update affects all the related entities too


Read More

Hibernate Interview Questions – Part 1

Hibernate Interview Questions – Part 1
(Hibernate Interview Questions Part 2)

What is Hibernate?
It is a open source and light weight ORM  tool
It is used to store, retrieve and manipulate the database.

What is ORM?
ORM stands for Object/Relational Mapping
Matching the object with data in database

What is Impedance Mismatch?
Object oriented applications use relational database to store and retrieve the data.
Object oriented application is in class while relational database represent the data in tabular format.
We can access class using Object but in order to access the data in relational database we need to use query.
The differences between Object Oriented and Relational Database is known as Impedance Mismatch

What are the types of Impedance Mismatch?
Difference between number of classes mapped with database tables
Differences in relationship among the classes and tables in database
Refers to how the objects are differentiated in application and relational database.(In database object is differentiated with Primary key, as in Object model it is distinguished based on object identity and equality)
Difference in linking classes in application and linking of tables in database.(One entity can have reference to another entity, but in relational database linking is done with help of foreign keys)

We use ORM to overcome impedance mismatch by mapping data representations of Object model having data types to relational data model with SQL data types

What are the Features of Hibernate?
– matches object model and relational database
Supports inheritance, polymorphism, abstraction and collections framework
Transparent Persistence – changes made in object are automatically detected and updated in database
Database Independent
Provides HQL similar to SQL

Explain Hibernate Architecture:
Consists of,
Configuration class:
 An instance of this class is created once during the initialization. This is used for reading and parsing the properties required to connect database and application
SessionFactory Interface:
Created using an object of Configuration class. This is used to create and open session to communicate with database. This is configured separately for each database being connected
Session Interface:
 Created with SessionFactory object and is used to communicate with database
Transaction Interface:
Created with help of Session Object and is used to perform logical unit of work from database
Query Interface:
Used to create query to perform operations in database
Criteria Interface:
Used to create query to perform database operations with conditions

How to create Hibernate Session?
 This method loads hibernate.cfg.xml file and initializes the object of Configuration class with configuration properties specified in xml file
 Used to fetch the properties  for configuration that are configured in configure()
Uses serviceRegistryBuilder to apply settings fetched from getProperties().
 Uses configuration object from Configure() and instantiate new SessionFactory Object. (ServiceRegistry object as parameter)

(Hibernate Interview Questions Part 2)

Read More

FLAMES game using Java

FLAMES game using Java
In this post we are going to see Java code for flames game. This is one of the commonly asked interview question. Before we go to the code, Let us see how are we going to solve this.

Step 1:
After getting the names, We are going to use StringBuilder to compare the names and replace the common matching characters into “0”.

Step 2:
After replacing with “0” we are going to remove the character “0” and count the length of both strings to get the value.

Step 3:
After getting the number, We are going to use the formula – x%flamesLength, i.e.
x = length of both strings after striking out matching characters
FlamesLength = Length of the flames as it get decremented on each iteration (As we strike out the characters one by one on each iteration)

int  y = x % flames.length() ;

There is one constraint here to make a note, When you strike characters in flames, on each iteration the counting starts from position ‘0’ in string. But as per flames game, for example – if the character “a” gets strike out the counting should start from the next character “m”. But on iterations the counting starts from initial position. To overcome this constraint we are going to use substring. (you can understand it from code)

Step 4:
After strikings when we get the last character, We are using the switch case to find the alphabet and give the meaning of that

Now let us see the code for Flames game,





Read More