Sunday, 21 April 2019

Explain lifecycle of a bean in Spring framework.

Spring Bean Life Cycle – Bean Initialization and Destruction

Spring IoC container is also responsible for managing the Spring Bean Life Cycle, the life cycle of beans consist of call back methods such as Post initialization call back method and Pre destruction call back method. Below steps are followed by Spring IoC Container to manage bean life cycle.

Spring Bean Life Cycle

Benefits of the Spring Framework

The following is the list of a few great benefits of using the Spring Framework:

Spring is a powerful framework, which address many common problems in Java EE. It includes support for managing business objects and exposing their services to presentation tier component.

It facilitates good programming practice such as programming using interfaces instead of classes. Spring enables developers to develop enterprise applications using POJO and POJI model programming.

Explain Spring Framework - Overview

Spring is the most popular application development framework for enterprise Java. Millions of developers around the world use Spring Framework to create high performing, easily testable, and reusable code.

Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.

Thursday, 18 April 2019

Difference between getCurrentSession() and openSession() in Hibernate ?

getCurrentSession() : 

The "current session" refers to a Hibernate Session bound by Hibernate behind the scenes, to the transaction scope.
A Session is opened when getCurrentSession() is called for the first time and closed when the transaction ends.
It is also flushed automatically before the transaction commits. You can call getCurrentSession() as

What is version checking in Hibernate ?

version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time)
and in the same time User B edit the same record for update and click the update.
Then User A click the Update and update done. Chnage made by user B is gone.

In hibernate you can perevent slate object updatation using version checking.

What is lazy fetching in Hibernate? With Example .


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.


What is the difference between hibernate and jdbc ?


There are so many differences between hibernate and jdbc, as follows

1) Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServer etc.

In case of JDBC query must be data base specific.

2) As Hibernate is set of Objects , you don?t need to learn SQL language.


Difference between session.save() , session.saveOrUpdate() and session.persist()?

session.save() : Save does an insert and will fail if the primary key is already persistent.

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.

session.persist() : Does the same like session.save().

But session.save() return Serializable object but session.persist() return void.


Sunday, 14 April 2019

How to configure Hibernate Second Level Cache using EHCache?


EHCache is the best choice for utilizing hibernate second level cache. Following steps are required to enable EHCache in hibernate application.

Add hibernate-ehcache dependency in your maven project, if it’s not maven then add corresponding jars.

What is Hibernate SessionFactory and how to configure it?

SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects. Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory.

The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.

SessionFactory also provide methods to get the Class metadata and Statistics instance to get the stats of query executions, second level cache details etc.

Name some important annotations used for Hibernate mapping?


Hibernate supports JPA annotations and it has some other annotations in org.hibernate.annotations package. Some of the important JPA and hibernate annotations used are:

javax.persistence.Entity: Used with model classes to specify that they are entity beans.
javax.persistence.Table: Used with entity beans to define the corresponding table name in database.
javax.persistence.Access: Used to define the access type, either field or property. Default value is field and if you want hibernate to use getter/setter methods then you need to set it to property.
javax.persistence.Id: Used to define the primary key in the entity bean.
javax.persistence.EmbeddedId: Used to define composite primary key in the entity bean.
javax.persistence.Column: Used to define the column name in database table.
javax.persistence.GeneratedValue: Used to define the strategy to be used for generation of primary key. Used in conjunction with javax.persistence.GenerationType enum.
javax.persistence.OneToOne: Used to define the one-to-one mapping between two entity beans. We have other similar annotations as OneToMany, ManyToOne and ManyToMany
org.hibernate.annotations.Cascade: Used to define the cascading between two entity beans, used with mappings. It works in conjunction with org.hibernate.annotations.CascadeType
javax.persistence.PrimaryKeyJoinColumn: Used to define the property for foreign key. Used with org.hibernate.annotations.GenericGenerator and org.hibernate.annotations.Parameter


Here are two classes showing usage of these annotations.

  1. import javax.persistence.Access;  
  2.   
  3. import javax.persistence.AccessType;  
  4.   
  5. import javax.persistence.Column;  
  6.   
  7. import javax.persistence.Entity;  
  8.   
  9. import javax.persistence.GeneratedValue;  
  10.   
  11. import javax.persistence.GenerationType;  
  12.   
  13. import javax.persistence.Id;  
  14.   
  15. import javax.persistence.OneToOne;  
  16.   
  17. import javax.persistence.Table;  
  18.   
  19.   
  20.   
  21. import org.hibernate.annotations.Cascade;  
  22.   
  23.   
  24.   
  25. @Entity  
  26.   
  27. @Table(name = "EMPLOYEE")  
  28.   
  29. @Access(value=AccessType.FIELD)  
  30.   
  31. public class Employee {  
  32.   
  33.   
  34.   
  35.     @Id  
  36.   
  37.     @GeneratedValue(strategy = GenerationType.IDENTITY)  
  38.   
  39.     @Column(name = "emp_id")  
  40.   
  41.     private long id;  
  42.   
  43.   
  44.   
  45.     @Column(name = "emp_name")  
  46.   
  47.     private String name;  
  48.   
  49.   
  50.   
  51.     @OneToOne(mappedBy = "employee")  
  52.   
  53.     @Cascade(value = org.hibernate.annotations.CascadeType.ALL)  
  54.   
  55.     private Address address;  
  56.   
  57.   
  58.   
  59.     //getter setter methods  
  60.   
  61. }  



  1. import javax.persistence.Access;  
  2.   
  3. import javax.persistence.AccessType;  
  4.   
  5. import javax.persistence.Column;  
  6.   
  7. import javax.persistence.Entity;  
  8.   
  9. import javax.persistence.GeneratedValue;  
  10.   
  11. import javax.persistence.Id;  
  12.   
  13. import javax.persistence.OneToOne;  
  14.   
  15. import javax.persistence.PrimaryKeyJoinColumn;  
  16.   
  17. import javax.persistence.Table;  
  18.   
  19.   
  20.   
  21. import org.hibernate.annotations.GenericGenerator;  
  22.   
  23. import org.hibernate.annotations.Parameter;  
  24.   
  25.   
  26.   
  27. @Entity  
  28.   
  29. @Table(name = "ADDRESS")  
  30.   
  31. @Access(value=AccessType.FIELD)  
  32.   
  33. public class Address {  
  34.   
  35.   
  36.   
  37.     @Id  
  38.   
  39.     @Column(name = "emp_id", unique = true, nullable = false)  
  40.   
  41.     @GeneratedValue(generator = "gen")  
  42.   
  43.     @GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") })  
  44.   
  45.     private long id;  
  46.   
  47.   
  48.   
  49.     @Column(name = "address_line1")  
  50.   
  51.     private String addressLine1;  
  52.   
  53.   
  54.   
  55.     @OneToOne  
  56.   
  57.     @PrimaryKeyJoinColumn  
  58.   
  59.     private Employee employee;  
  60.   
  61.   
  62.   
  63.     //getter setter methods  
  64.   
  65. }  

What’s Transaction Management In Hibernate? How It Works?

Transaction management is the process of managing a set of statements or commands. In hibernate; transaction management is done by transaction interface as shown in below code:

  1. Session s = null;  
  2.   
  3. Transaction tr = null;  
  4.   
  5. try {  
  6.   
  7. s = sessionFactory.openSession();  
  8.   
  9. tr = s.beginTransaction();  
  10.   
  11. doTheAction(s);  
  12.   
  13. tr.commit();  
  14.   
  15. catch (RuntimeException exc) {  
  16.   
  17. tr.rollback();  
  18.   
  19. finally {  
  20.   
  21. s.close();  
  22.   
  23. }  

How Can We Invoke Stored Procedures In Hibernate?


In hibernate we can execute stored procedures using code as below:
  1. [xml]  
  2.   
  3. <sql-query name=”getStudents” callable=”true”>  
  4.   
  5. <return alias=”st” class=”Student”>  
  6.   
  7. <return-property name=”std_id” column=”STD_ID”/>  
  8.   
  9. <return-property name=”s_name” column=”STD_NAME”/>  
  10.   
  11. <return-property name=”s_dept” column=”STD_DEPARTMENT”/>  
  12.   
  13. { ? = call selectStudents() }  
  14.   
  15. </return>  
  16.   
  17. </sql-query>  
  18.   
  19. [/xml]  

Spring Boot @ConfigurationProperties and Properties File

 In this tutorial, you will learn to use @ConfigurationProperties to map properties files to POJO classes in Spring Boot application. Let’s ...