Hibernate Interview Questions – Part 6

Hibernate Interview Questions – Part 6
Implementing Concurrency

What is Concurrency?
Each transaction is Hibernate is isolated from another transaction. So one transaction is not aware of another transaction. Which results in high possibility of a same record in database may be accessed by two or more transactions at same time. When multiple transactions access the same record in database and make changes concurrency issue occurs as data becomes inconsistent.

Concurrency Issues:
Dirty Read:
A transaction reads the data that has not been committed by another transaction

Lost Updates:
When two or more transactions try to access same row this issue occurs. Transactions overwrite the data on same row again and again leading to loss of data manipulation

Nonrepeatable Read:
Transaction reads the same row more than once and another transaction changes the data in the row between the successive reads of the transaction

Phantom Read:
A transaction reads a rowset more than once and another transaction inserts or deletes a row between the successive reads.


How to Control Concurrency Issues?
Setting transaction isolation levels
Implementing versioning
Implementing Locks


Setting Transaction Isolation Levels:
Read Uncommitted: 

In this level, a transaction can read the data modified by another transaction. But a transaction can read the data modified by another transaction even before the commit is made. Dirty Reads, Lost Updates, Nonrepeatable Read and Phantom read all issues occur at this level
Isolation Level – 1

Read Committed:
This is the default Isolation level in SQL database. In this level, When a transaction modifies a data other transactions will not be able to read the modified data. This prevents Dirty Reads but Lost Updates, Nonrepeatable Read and Phantom Read occurs at this level
Isolation Level – 2

Repeatable Read:
In this level, When a transaction is modifying a data no other transactions can Read or Update the data until the current transaction completes it process. At this level, Dirty Reads, Lost Updates and Nonrepeatable Read are prevented but Phantom Read may occur
Isolation Level – 4

Serializable:
In this level, When a transaction is modifying a data no other transaction can read, update, modify or insert data until the current transaction completes its process and commits.
Isolation Level – 8

1


Implementing Versioning:
In this method, version information is added to the persistent entities. Each entity has a version that represents the state of that entity. These version information are stored in a column in a database or timestamp that shows the time the data last modified.

How this Works?
When a record is modified in the database, hibernate increments the version number or timestamp of that record. So when another transaction tries to update the data, Hibernate will check for the version number or timestamp with the version or Timestamp of the transaction and throws exception it the transaction carries older version number


Implementing Locks:
We can implement the Locks when data’s are retrieved from database or when updating in database. Session interface provides lock() method.

LockMode.READ:
This acquires  lock when record is read from database

LockMode.UPGRADE:
This acquires database-level lock for persistent objects that are going to update.

LockMode.WRITE:
This acquires  lock when data is updated or inserted


 

Read More

Hibernate Interview Questions – Part 5

Hibernate Interview Questions – Part 5
Part 1, Part 2, Part 3, Part 4
Persistent Objects and Transactions

Different Object States in Hibernate?
Transient
Persistent
Detached


Transient:
An object created using new Operator is known in Transient State. This object is not associated with database.

Persistent:
When a Transient object with values are stored in database, then the object is said to be in Persistent State.

Detached State:
When an object is saved in the database and the hibernate session is closed, The object is said to be in Detached State


What is a Transaction?
Transaction is a sequence of operations performed.


Properties of Transactions?
Every transaction should have the following ACID properties,
Atomic : All the modifications to be performed or none to be performed
Consistency: All data should be consistent once the transaction has been completed
Isolation: Every transaction should be Isolated from another transaction
Durability: Data change in a system after the transaction is completed should remain permanent in the System.


States of Transactions:
Active:
when transaction is created and ready for execution.

Partially Committed:
When all the operations are performed but the transaction is not yet committed.

Failed:
When transaction is failed and cannot proceed further.

Aborted:
Transaction is failed and the operations of transactions are rolled back.

Committed:
Transaction is success and all the changes are committed and saved in database.

Terminated:
When transaction is completed successfully or when transaction is failed this state occurs.


Methods to Configure Transactions:
void begin():
Starts the transaction.

void commit():
Ends the work.

void rollback():
Reverse the changes.

boolean wasCommitted():
checks whether the transaction is committed or not.

boolean wasRolledBack():
checks if transaction is rolledback or not.


 

Read More

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.


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



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

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

WHERE:
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

Example 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:
<DOCTYPE>:
Specifies the type of XML and the name of Document Type Definition(DTD) contains rule to validate elements

<hibernate-mapping>:
Root of mapping elements

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

<id>:
Primary key column of database.
Attributes:
name
– 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.

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

<property>:
Maps properties of Java class with database columns
Attributes:
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

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


Explain mapping using Annotations:
@Entity
– 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?
Granularity:
Difference between number of classes mapped with database tables
Subtypes:
Differences in relationship among the classes and tables in database
Identity:
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)
Association:
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?
ORM
– 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?
configure():
 This method loads hibernate.cfg.xml file and initializes the object of Configuration class with configuration properties specified in xml file
getProperties():
 Used to fetch the properties  for configuration that are configured in configure()
applySettings():
Uses serviceRegistryBuilder to apply settings fetched from getProperties().
buildSessionFactory():
 Uses configuration object from Configure() and instantiate new SessionFactory Object. (ServiceRegistry object as parameter)

(Hibernate Interview Questions Part 2)


Read More