
Domains
Agile Management
Master Agile methodologies for efficient and timely project delivery.
View All Agile Management Coursesicon-refresh-cwCertifications
Scrum Alliance
16 Hours
Best Seller
Certified ScrumMaster (CSM) CertificationScrum Alliance
16 Hours
Best Seller
Certified Scrum Product Owner (CSPO) CertificationScaled Agile
16 Hours
Trending
Leading SAFe 6.0 CertificationScrum.org
16 Hours
Professional Scrum Master (PSM) CertificationScaled Agile
16 Hours
SAFe 6.0 Scrum Master (SSM) CertificationAdvanced Certifications
Scaled Agile, Inc.
32 Hours
Recommended
Implementing SAFe 6.0 (SPC) CertificationScaled Agile, Inc.
24 Hours
SAFe 6.0 Release Train Engineer (RTE) CertificationScaled Agile, Inc.
16 Hours
Trending
SAFe® 6.0 Product Owner/Product Manager (POPM)IC Agile
24 Hours
ICP Agile Certified Coaching (ICP-ACC)Scrum.org
16 Hours
Professional Scrum Product Owner I (PSPO I) TrainingMasters
32 Hours
Trending
Agile Management Master's Program32 Hours
Agile Excellence Master's ProgramOn-Demand Courses
Agile and ScrumRoles
Scrum MasterTech Courses and Bootcamps
Full Stack Developer BootcampAccreditation Bodies
Scrum AllianceTop Resources
Scrum TutorialProject Management
Gain expert skills to lead projects to success and timely completion.
View All Project Management Coursesicon-standCertifications
PMI
36 Hours
Best Seller
Project Management Professional (PMP) CertificationAxelos
32 Hours
PRINCE2 Foundation & Practitioner CertificationAxelos
16 Hours
PRINCE2 Foundation CertificationAxelos
16 Hours
PRINCE2 Practitioner CertificationSkills
Change ManagementMasters
Job Oriented
45 Hours
Trending
Project Management Master's ProgramUniversity Programs
45 Hours
Trending
Project Management Master's ProgramOn-Demand Courses
PRINCE2 Practitioner CourseRoles
Project ManagerAccreditation Bodies
PMITop Resources
Theories of MotivationCloud Computing
Learn to harness the cloud to deliver computing resources efficiently.
View All Cloud Computing Coursesicon-cloud-snowingCertifications
AWS
32 Hours
Best Seller
AWS Certified Solutions Architect - AssociateAWS
32 Hours
AWS Cloud Practitioner CertificationAWS
24 Hours
AWS DevOps CertificationMicrosoft
16 Hours
Azure Fundamentals CertificationMicrosoft
24 Hours
Best Seller
Azure Administrator CertificationMicrosoft
45 Hours
Recommended
Azure Data Engineer CertificationMicrosoft
32 Hours
Azure Solution Architect CertificationMicrosoft
40 Hours
Azure DevOps CertificationAWS
24 Hours
Systems Operations on AWS Certification TrainingAWS
24 Hours
Developing on AWSMasters
Job Oriented
48 Hours
New
AWS Cloud Architect Masters ProgramBootcamps
Career Kickstarter
100 Hours
Trending
Cloud Engineer BootcampRoles
Cloud EngineerOn-Demand Courses
AWS Certified Developer Associate - Complete GuideAuthorized Partners of
AWSTop Resources
Scrum TutorialIT Service Management
Understand how to plan, design, and optimize IT services efficiently.
View All DevOps Coursesicon-git-commitCertifications
Axelos
16 Hours
Best Seller
ITIL 4 Foundation CertificationAxelos
16 Hours
ITIL Practitioner CertificationPeopleCert
16 Hours
ISO 14001 Foundation CertificationPeopleCert
16 Hours
ISO 20000 CertificationPeopleCert
24 Hours
ISO 27000 Foundation CertificationAxelos
24 Hours
ITIL 4 Specialist: Create, Deliver and Support TrainingAxelos
24 Hours
ITIL 4 Specialist: Drive Stakeholder Value TrainingAxelos
16 Hours
ITIL 4 Strategist Direct, Plan and Improve TrainingOn-Demand Courses
ITIL 4 Specialist: Create, Deliver and Support ExamTop Resources
ITIL Practice TestData Science
Unlock valuable insights from data with advanced analytics.
View All Data Science Coursesicon-dataBootcamps
Job Oriented
6 Months
Trending
Data Science BootcampJob Oriented
289 Hours
Data Engineer BootcampJob Oriented
6 Months
Data Analyst BootcampJob Oriented
288 Hours
New
AI Engineer BootcampSkills
Data Science with PythonRoles
Data ScientistOn-Demand Courses
Data Analysis Using ExcelTop Resources
Machine Learning TutorialDevOps
Automate and streamline the delivery of products and services.
View All DevOps Coursesicon-terminal-squareCertifications
DevOps Institute
16 Hours
Best Seller
DevOps Foundation CertificationCNCF
32 Hours
New
Certified Kubernetes AdministratorDevops Institute
16 Hours
Devops LeaderSkills
KubernetesRoles
DevOps EngineerOn-Demand Courses
CI/CD with Jenkins XGlobal Accreditations
DevOps InstituteTop Resources
Top DevOps ProjectsBI And Visualization
Understand how to transform data into actionable, measurable insights.
View All BI And Visualization Coursesicon-microscopeBI and Visualization Tools
Certification
24 Hours
Recommended
Tableau CertificationCertification
24 Hours
Data Visualization with Tableau CertificationMicrosoft
24 Hours
Best Seller
Microsoft Power BI CertificationTIBCO
36 Hours
TIBCO Spotfire TrainingCertification
30 Hours
Data Visualization with QlikView CertificationCertification
16 Hours
Sisense BI CertificationOn-Demand Courses
Data Visualization Using Tableau TrainingTop Resources
Python Data Viz LibsCyber Security
Understand how to protect data and systems from threats or disasters.
View All Cyber Security Coursesicon-refresh-cwCertifications
CompTIA
40 Hours
Best Seller
CompTIA Security+EC-Council
40 Hours
Certified Ethical Hacker (CEH v12) CertificationISACA
22 Hours
Certified Information Systems Auditor (CISA) CertificationISACA
40 Hours
Certified Information Security Manager (CISM) Certification(ISC)²
40 Hours
Certified Information Systems Security Professional (CISSP)(ISC)²
40 Hours
Certified Cloud Security Professional (CCSP) Certification16 Hours
Certified Information Privacy Professional - Europe (CIPP-E) CertificationISACA
16 Hours
COBIT5 Foundation16 Hours
Payment Card Industry Security Standards (PCI-DSS) CertificationOn-Demand Courses
CISSPTop Resources
Laptops for IT SecurityWeb Development
Learn to create user-friendly, fast, and dynamic web applications.
View All Web Development Coursesicon-codeBootcamps
Career Kickstarter
6 Months
Best Seller
Full-Stack Developer BootcampJob Oriented
3 Months
Best Seller
UI/UX Design BootcampEnterprise Recommended
6 Months
Java Full Stack Developer BootcampCareer Kickstarter
490+ Hours
Front-End Development BootcampCareer Accelerator
4 Months
Backend Development Bootcamp (Node JS)Skills
ReactOn-Demand Courses
Angular TrainingTop Resources
Top HTML ProjectsBlockchain
Understand how transactions and databases work in blockchain technology.
View All Blockchain Coursesicon-stop-squareBlockchain Certifications
40 Hours
Blockchain Professional Certification32 Hours
Blockchain Solutions Architect Certification32 Hours
Blockchain Security Engineer Certification24 Hours
Blockchain Quality Engineer Certification5+ Hours
Blockchain 101 CertificationOn-Demand Courses
NFT Essentials 101: A Beginner's GuideTop Resources
Blockchain Interview QsProgramming
Learn to code efficiently and design software that solves problems.
View All Programming Coursesicon-codeSkills
Python CertificationInterview Prep
Career Accelerator
3 Months
Software Engineer Interview PrepOn-Demand Courses
Data Structures and Algorithms with JavaScriptTop Resources
Python TutorialProgramming
4.7 Rating 32 Questions 20 mins read11 Readers

POJO stands for Plain Old Java Object. Hibernate is based on the concept of taking values from Java class attributes and storing them in a database. Such classes whose objects are stored in a database are known as persistent classes. These classes have proper getter and setter methods for every property. These classes also have a default constructor. These classes should be non-final or have an interface with all the public methods declared. An ID is mandatory for each object of these classes as they will be mapped to the primary column of the table. Use of POJOs instead of simple java classes results in an efficient and well – constructed code. A simple example of a POJO class is as below:
public class Student{ private int id; private String firstName; private String lastName; private int age; public Employee(){} public Employee(String fname,String lname,int age){ this.firstName=fname; this.lastName=lname; this.age= age; } public int getId(){return id; } public void setId(int id ){ this.id = id;} public String getFirstName(){ return firstName;} public void setFirstName(String first_name){ this.firstName=first_name; } public String getLastName(){ return lastName; } public void setLastName(String last_name){ this.lastName=last_name; } public int getAge(){ return age; } public void setAge(int age ){ this.age= age; } }
Derived properties are properties that are not mapped to any column of a database table. They are also known as calculated properties and are calculated at runtime. These properties are read-only in nature and can be defined using the @Formula annotation or by using the <formula> tag in the hbm.xml definition file. To use the @Formula annotation, we need to import org.hibernate.annotations.Formula package.
Let us look at an example.
@Entity
@Table(name="EMPLOYEE")
public class Employee implements java.io.Serializable {
@Id
@Column(name="ID")
private Integer id;
@Column(name="FIRST_NAME", length=50)
private String firstName;
@Column(name="LAST_NAME", length=50)
private String lastName;
@Column(name="MONTHLY_SALARY")
private float monthlySalary;
@Formula("MONTHLY_SALARY*12")
private float yearlySalary;
public Employee() { }
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getFirstName() { return firstName; }
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public float getMonthlySalary() { return monthlySalary; }
public void setMonthlySalary(float monthlySalary) {
this.monthlySalary = monthlySalary;
}
public float getYearlySalary() { return yearlySalary; }
} In the above example, the @Formula annotation refers to the MONTHLY_SALARY column in the database table and not the monthlySalary property in the class.
The hbm mapping for the above class would be: <?xml version="1.0"?> <!DOCTYPEhibernate-mappingPUBLIC"-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.other.domain.entity.Employee" table="EMPLOYEE"> <id name="id" type="integer" access="property"unsaved-value="null"> <column name="ID"/> <generator class="native"/> </id> <property name="firstName" type="string" column="FIRST_NAME"/> <property name="lastName" type="string" column="LAST_NAME"/> <property name="monthlySalary" type="float" column="MONTHLY_SALARY"/> <property name="yearlySalary" type="float" column="YEARLY_SALARY" formula="(SELECT (MONTHLYSALARY*12) from EMPLOYEE e where e.id = ID)"/> </class> </hibernate-mapping>
This is a frequently asked question in hibernate interview questions for freshers.
The Hibernate collections behave like HashMap, HashSet, TreeMap, TreeSet or ArrayList. Collection instances are like value types and are automatically persisted when referenced by a persistent object and deleted when unreferenced. There are five types of collections in Hibernate. They are:
To map these collections, the type of collection must be declared from one of the following:
The Hibernate mapping element used for mapping a collection depends upon the type of interface. The basic syntax for mapping is:
<hibernate-mapping> <class name="<event.Class>" table="<TableName>"> <id name="id" column="<ColumnName>"> <generator class="native"/> </id> <property name="<property>" type="<type>" column="<ColumnName>"/> <property name="<property>"/> <set name = “<name of set>”> <key column=“<column name>” not-null= “true”/> <one-to-many class=“<associated class>”/> </set> </class> </hibernate-mapping>
The <set> can be replaced with map, list etc. There are different associations for mapping the class with the corresponding table. The types of associations are as below:
When using a map for mapping, a map-key has to be provided along with the key column.
<map name="developmentLanguages" table="tdevelopmentlanguage" cascade="all"> <key column="developer_id" not-null="true"></key> <map-key type="string" column="shortname"></map-key> <element column="name" type="string"></element> </map>
A proxy is defined as a function which acts as a substitute to another function. When a load() method is called on session, a proxy is returned and this proxy contains the actual method to load the data.
The session.load() method creates an uninitialized proxy object for our desired entity class. The proxy implementation delegates all property methods except for the @id to the session which will in turn populate the instance. When an entity method is called, the entity is loaded and the proxy becomes an initialized proxy object.
Let us understand this with an example. Let us assume that there is an entity called Student. Let us also assume that initially, this entity has no connection or relation with any other tables except the Student table. When the session.load() method is called to instantiate the Student,
Student dia = session.load(Student.class, newLong(1));
Hibernate will create an uninitialized proxy for this entity with the id we have assigned it and will contain no other property as we have not yet communicated with the database. However, when a method is called on dia,
String firstName = dia.getFirstName();
Hibernate will fire a query to the database for information on the student with primary key 1 and populates the object dia with the properties from the corresponding row. If the row is not found, Hibernate throws an ObjectNotFoundException
The session object is used to connect with a database. It is light-weight and is instantiated every time a database connection is required. Sessions are not thread safe and so should not be kept open for long. These objects should be created as needed and should be destroyed if not in use. Sessions hold a first-level cache of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria.
The main functionality of Session objects is to provide create, read and delete operations to the instances of the mapped entity classes. The instances may be in one of the following states at any given point.
A session instance becomes serializable if its persistent class or classes is/are serialised. If a session throws an error, the transaction has to be rolled back and the session instance has to be deleted.
A common question in hibernate interview questions for experienced, don't miss this one.
Concurrency strategies act as mediators. They are responsible for storing items and retrieving them from the cache. If the developer wants to enable a second-level cache, the developer must decide to do it for each persistent class and collection. The developer must also decide which cache concurrency has to be implemented.
The concurrency strategies that the developer can implement are as follows:
These strategies are used with second - level cache. An example of the usage of these strategies is shown in the below example, where we add a mapping element to the configuration file to inform Hibernate to cache the persistent class instances using the read-write strategy. We are using the Employee class in this example.
<hibernate-mapping> <class name = "Employee" table = "EMPLOYEE"> <meta attribute = "class-description"> This class contains the employee detail. </meta> <cache usage = "read-write"/> <id name = "id" type = "int" column = "id"> <generator class="native"/> </id> <property name = "firstName" column = "first_name" type = "string"/> <property name = "lastName" column = "last_name" type = "string"/> <property name = "salary" column = "salary" type = "int"/> </class> </hibernate-mapping>
Hibernate has a feature to monitor all persistent object properties. Whenever an entity is loaded through hibernate, it makes an additional copy of that whole entity object along with all the entity's property values. Irrespective of a change in one property or multiple properties, Hibernate checks all the objects properties. It detects which objects have been modified and then calls update statements on all updated objects. Once the changes or modifications are identified, a transaction is performed using the session object. So, if a session object is open and an object property is modified, the data is synchronized in the database. The data will be synchronized but will not be committed, till the session object's commit() method or flush() method is called. Both synchronization and committing of code will happen together when the commit method is called. This process of monitoring all the persistent or managed objects and updating only the changed object properties is called automatic dirty checking. Dirty checking helps the user or developer to avoid the time-consuming database write actions. This feature makes necessary updates or changes to the fields based on the changes made to the objects of the mapped class and the remaining fields are left unchanged or untouched.
This is a frequently asked hibernate interview questions and answers for experienced
EHCache is the best choice for utilizing hibernate second level cache. Following steps are required to enable EHCache in hibernate application.
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-ehcache</artifactId> <version>4.3.5.Final</version> </dependency>
<property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</property> <!-- For singleton factory --> <!-- <property name="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.SingletonEhCacheRegionFactory</property> --> <!-- enable second level cache and query cache --> <property name="hibernate.cache.use_second_level_cache">true</property> <property name="hibernate.cache.use_query_cache">true</property> <property name="net.sf.ehcache.configurationResourceName">/myehcache.xml</property>
<?xml version="1.0" encoding="UTF-8"?> <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="ehcache.xsd"updateCheck="true" monitoring="autodetect"dynamicConfig="true"> <diskStorepath="java.io.tmpdir/ehcache" /> <defaultCachemaxEntriesLocalHeap="10000"eternal="false" timeToIdleSeconds="120"timeToLiveSeconds="120"diskSpoolBufferSizeMB="30" maxEntriesLocalDisk="10000000"diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"statistics="true"> <persistence strategy="localTempSwap" /> </defaultCache> <cache name="employee" maxEntriesLocalHeap="10000"eternal="false" timeToIdleSeconds="5"timeToLiveSeconds="10"> <persistence strategy="localTempSwap" /> </cache> <cache name="org.hibernate.cache.internal.StandardQueryCache" maxEntriesLocalHeap="5"eternal="false"timeToLiveSeconds="120"> <persistence strategy="localTempSwap" /> </cache> <cache name="org.hibernate.cache.spi.UpdateTimestampsCache" maxEntriesLocalHeap="5000"eternal="true"> <persistence strategy="localTempSwap" /> </cache> </ehcache>
import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "ADDRESS") @Cache(usage=CacheConcurrencyStrategy.READ_ONLY, region="employee") public class Address { }
Hibernate will now use the EHCache for second level caching.
Cascading means when an insert, update or delete operation occurs on one entity, its related entities also are inserted, updated or deleted. If cascading is not used, the objects will have to be saved independently and explicitly.
import org.hibernate.annotations.Cascade; @Entity @Table(name = "EMPLOYEE") public class Employee { @OneToOne(mappedBy = "employee") @Cascade(value = org.hibernate.annotations.CascadeType.ALL) public Department dept; }
The CascadeTypeenum constants of Hibernate are slightly different from JPA. As shown in the above example, we use. CascadeType and Cascade annotations for mappings. The commonly used cascading types as defined in CascadeTypeenum are:
Validating data is an integral part of any application and happens in all the application layers. Most of the time, the same validations are replicated across the layers making it error-prone and time-consuming. To avoid duplication of the validation logic, JSR 380 defines a metadata model and API for data validation i.e. entity and method validation. Hibernate Validator is the reference implementation of JSR380. When Hibernate Validator is used in an application, it will also require an implementation of the Unified Expression Language (JSR341) for evaluating dynamic expressions as well as the Hibernate Validator dependencies. Let us understand the Hibernate Validator with an example:
<dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.1.1.Final</version> </dependency>
Let us create an Employee class:
import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.hibernate.validator.constraints.CreditCardNumber; import org.hibernate.validator.constraints.Email; public class Employee { @Min(value=1, groups=EmpIdCheck.class) private int id; @NotNull(message="Name cannot be null") @Size(min=5, max=30) private String name; @Email private String email; @CreditCardNumber private String creditCardNumber; //default no-args constructor public Employee(){} public Employee(int id, String name, String email, String ccNum){ this.id=id; this.name=name; this.email=email; this.creditCardNumber=ccNum; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCreditCardNumber() { return creditCardNumber; } public void setCreditCardNumber(String creditCardNumber) { this.creditCardNumber = creditCardNumber; } }
Hibernate validator provides very good validation annotations like @Email and @CreditCardNumber which avoids usage of implementation specific annotations which lead to loose coupling.
Hibernate Validator also allows us to define Custom Error Messages which we can configure in the ValidationMessages.properties file in the classpath. The file looks like:
#Hibernate Bug for @CreditCardNumber Workaround - https://hibernate.atlassian.net/browse/HV-881
org.hibernate.validator.constraints.LuhnCheck.message=The check digit for ${validatedValue} is invalid, Luhn Modulo 10 checksum failed.
org.hibernate.validator.constraints.Email.message=Invalid email address