Spring Hibernate Integration Example – CRUD Operations

Spring Hibernate Integration Example – CRUD Operations
In this article, We are going to see how to perform CRUD Operations with the help of Spring and Hibernate. We are going to use Spring Dependency Injection concept and we are also going to declare Hibernate Properties in Spring Application Context XML file.

I have downloaded and used some jar files in this application,
Jar files Needed:
org.apache.commons.dbcp.jar
commons-pool-1.6.jar
Other than this, Spring Framework, Hibernate and MySQL JDBC Driver are required

Here is the application Structure,
structure

javainfinite.pojo

javainfinite.DAO

javainfinite.DAOImpl

applicationContext.xml

javainfinite.execution

Output:

op1 op2

 Download Source code (Src Files – applicationContext.xml, pojo, DAO, DAOImpl and execution)

 

 

 

Read More

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 3

Hibernate Interview Questions – Part 3

Hibernate Interview Questions – Part 1Part 2

Explain One – to – One Mapping:
Example:
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:
Example:
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