Upwork Test Answers: Get all the correct answers of most recent and possible Upwork Tests A to Z (Updated on Jan, 2016)
Cover Letter Templates: These cover letter samples are not only for Upwork job, but also you will have some idea about your real life job
Freelance Profile Overviews: Different Profile samples and overviews of experts, advanced and intermediate level freelancers
For Newbie of Upwork: Upwork Help - How to apply for a job in Upwork with 10 most important articles about Upwork

A to Z View - All Upwork Test Answers

Hibernate - Interview questions and answers

These Interview Questions and answers are not only for Upwork job, you will have some idea about the related job interview for your permanent or real life job.  This is just some sample answers, don't just copy and paste them, read them carefully and make your own answer.

In this post, you will find all the possible and most recent Job Interview questions and answers of Hibernate for JAVA category which you might be asked by your employer. These interview questions and answers will help you to get the job.
1. How can we get hibernate statistics?
We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below:

2. How can we invoke stored procedures in hibernate?
In hibernate we can execute stored procedures using code as below:
{ ? = call selectStudents() }

3. How can we reduce database write action times in Hibernate?
Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.

4. How can we see hibernate generated SQL on console?
We need to add following in hibernate configuration file to enable viewing SQL on the console

for debugging purposes:

5. How do we create session factory in hibernate?
To create a session factory in hibernate, an object of configuration is created first which refers to the path of configuration file and then for that configuration, session factory is created as given in the example below:
Configuration config = new Configuration();
config.setProperties( System.getProperties() );
SessionFactory sessions = config.buildSessionFactory();

6. How do you define sequence generated primary key in hibernate?
Using <generator> tag.
<id column="CUST_ID" name="id" type="java.lang.Long">
<generator class="sequence">
<param name="table">SEQUENCE_NAME</param>

7. How mapping of java objects is done with database tables?
To map java objects with database tables, we need to have Java beans properties names same as column names of a database table. Then mapping is provided in hbm.xml file as given below:

8. How primary key is created by using hibernate?
Database primary key is specified in the configuration file hbm.xml. Generator can also be used to specify how primary key is being created in the database.
In the below example, deptId acts as primary key:

9. How to integrate Hibernate and Spring frameworks?
Spring is one of the most used Java EE Framework and Hibernate is the most popular ORM framework.
That’s why Spring Hibernate combination is used a lot in enterprise applications.
The best part with using Spring is that it provides out-of-box integration support for Hibernate with Spring ORM module.
Following steps are required to integrate Spring and Hibernate frameworks together.

• Add hibernate-entity manager, hibernate-core and spring-orm dependencies.
• Create Model classes and corresponding DAO implementations for database operations.
Note that DAO classes will use SessionFactory that will be injected by Spring Bean configuration.
• If you are using Hibernate 3, you need to configure org.springframework.orm.hibernate3.LocalSessionFactoryBean
ororg.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean in Spring Bean configuration file.
For Hibernate 4, there is single classorg.springframework.orm.hibernate4.
LocalSessionFactoryBean that should be configured.
• Note that we don’t need to use Hibernate Transaction Management, we can leave it to Spring declarative transaction management using @Transactional annotation.

10. How to log hibernate generated sql queries in log files?
We can set below property for hibernate configuration to log SQL queries.

<property name="hibernate.show_sql">true</property>

However, we should use it only in Development or Testing environment and turn it off in production environment.

11. How to use application server JNDI DataSource with Hibernate framework?
For web applications, it’s always best to allow servlet container to manage the connection pool.
That’s why we define JNDI resource for DataSource and we can use it in the web application.
It’s very easy to use in Hibernate, all we need is to remove all the database specific
properties and use below property to provide the JNDI DataSource name.

<property name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB</property>

12. In how many ways objects can be identified in Hibernate?
Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent the same

13. In how many ways, objects can be fetched from database in hibernate?
Hibernate provides following four ways to fetch objects from database:
a. Using HQL
b. Using identifier
c. Using Criteria API
d. Using Standard SQL

14. 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.

package com.journaldev.hibernate.model; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; import org.hibernate.annotations.Cascade; @Entity @Table(name = "EMPLOYEE") @Access(value=AccessType.FIELD) public class Employee { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "emp_id") private long id; @Column(name = "emp_name") private String name; @OneToOne(mappedBy = "employee") @Cascade(value = org.hibernate.annotations.CascadeType.ALL) private Address address; //getter setter methods }

package com.journaldev.hibernate.model; import javax.persistence.Access; import javax.persistence.AccessType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.PrimaryKeyJoinColumn; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; import org.hibernate.annotations.Parameter; @Entity @Table(name = "ADDRESS") @Access(value=AccessType.FIELD) public class Address { @Id @Column(name = "emp_id", unique = true, nullable = false) @GeneratedValue(generator = "gen") @GenericGenerator(name = "gen", strategy = "foreign", parameters = { @Parameter(name = "property", value = "employee") }) private long id; @Column(name = "address_line1") private String addressLine1; @OneToOne @PrimaryKeyJoinColumn private Employee employee; //getter setter methods }

15. What are different ways to disable hibernate second level cache?
Hibernate second level cache can be disabled using any of the following ways:
a. By setting use_second_level_cache as false.
c. Using cache provider as org.hibernate.cache.NoCacheProvider

16. What are POJOs and what's their significance?
POJOs( Plain Old Java Objects) are java beans with proper getter and setter methods for each
and every properties.
Use of POJOs instead of simple java classes results in an efficient and well constructed code.

17. What are the benefits of using Hibernate template?
Following are some key benefits of using Hibernate template:
a. Session closing is automated.
b. Interaction with hibernate session is simplified.
c. Exception handling is automated.

18. What different fetching strategies are of hibernate?
Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching

19. What is attribute oriented programming?
In Attribute oriented programming, a developer can add Meta data (attributes) in the java source
code to add more significance in the code. For Java (hibernate), attribute oriented programming
is enabled by an engine called XDoclet.

20. What is cascading and what are different types of cascading?
When we have relationship between entities, then we need to define how the different operations will affect the other entity. This is done by cascading and there are different types of it.

Here is a simple example of applying cascading between primary and secondary entities.

import org.hibernate.annotations.Cascade; @Entity @Table(name = "EMPLOYEE") public class Employee { @OneToOne(mappedBy = "employee") @Cascade(value = org.hibernate.annotations.CascadeType.ALL) private Address address; }

Note that Hibernate CascadeType enum constants are little bit different from JPA javax.persistence.CascadeType, so we need to use the Hibernate CascadeType and Cascade annotations for mappings, as shown in above example.
Commonly used cascading types as defined in CascadeType enum are:

• None: No Cascading, it’s not a type but when we don’t define any cascading then no operations in parent affects the child.
• ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically everything
• SAVE_UPDATE: Cascades save and update, available only in hibernate.
• DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
• DETATCH, MERGE, PERSIST, REFRESH and REMOVE – for similar operations
• LOCK: Corresponds to the Hibernate native LOCK action.
• REPLICATE: Corresponds to the Hibernate native REPLICATE action.

21. What is difference between Hibernate save(), saveOrUpdate() and persist() methods?
Hibernate save can be used to save entity to database. Problem with save() is that it can be invoked without a transaction and if we have mapping entities, then only the primary object gets saved causing data inconsistencies. Also, save returns the generated id immediately.

Hibernate persist is similar to save with transaction. I feel it’s better than save because we can’t use it outside the boundary of the transaction, so all the object mappings are preserved. Also persist doesn’t return the generated id immediately, so data persistence happens when needed.

Hibernate saveOrUpdate results into insert or update queries based on the provided data. If the data is present in the database, update query is executed. We can use saveOrUpdate() without transaction also, but again you will face the issues with mapped objects not getting saved if the session is not flushed.

22. What is the difference between sorted collection and ordered collection, which one is better?
When we use Collection API sorting algorithms to sort a collection, it’s called sorted list. For small collections, it’s not much of an overhead but for larger collections it can lead to slow performance and OutOfMemory errors. Also the entity beans should implement Comparable or Comparator interface for it to work.

If we are using Hibernate framework to load collection data from database, we can use it’s Criteria API to use “order by” clause to get ordered list. Below code snippet shows you how to get it.

List<Employee> empList = session.createCriteria(Employee.class) .addOrder(Order.desc("id")).list();

An ordered list is better than the sorted list because the actual sorting is done at the database level, that is fast and doesn’t cause memory issues.

23. What is hibernate caching? Explain Hibernate first level cache?
As the name suggests, hibernate caches query data to make our application faster. Hibernate Cache can be very useful in gaining fast application performance if used correctly. The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application.

Hibernate first level cache is associated with the Session object. Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely.
Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.

24. What is HibernateTemplate class?
When Spring and Hibernate integration started, Spring ORM provided two helper classes – HibernateDaoSupport and HibernateTemplate. The reason to use them was to get the Session from Hibernate and get the benefit of Spring transaction management. However from Hibernate 3.0.1, we can use SessionFactory getCurrentSession() method to get the current session and use it to get the spring transaction management benefits. If you go through above examples, you will see how easy it is and that’s why we should not use these classes anymore.

One other benefit of HibernateTemplate was exception translation but that can be achieved easily by using @Repository annotation with service classes, shown in above spring mvc example. This is a trick question to judge your knowledge and whether you are aware of recent developments or not.

25. What is meant by a Named SQL Query in hibernate and how it's used?
Named SQL queries are those queries which are defined in mapping file and are called as required anywhere. For example, we can write a SQL query in our XML mapping file as follows:
std.STUDENT_DISCIPLINE AS {std.discipline},
FROM Student std WHERE std.NAME LIKE :name

Then this query can be called as follows:
List students = session.getNamedQuery(&quot;studentdetails&quot;)
.setString(&quot;TomBrady&quot;, name)

26. What is ORM?
ORM (Object Relational Mapping) is the fundamental concept of Hibernate framework which maps database tables with Java Objects and then provides various API's to perform different types of operations on the data tables.

27. What is Query Cache in Hibernate?
Hibernate implements a cache region for queries resultset that integrates closely with the hibernate second-level cache.

This is an optional feature and requires additional steps in code. This is only useful for queries that are run frequently with the same parameters., First of all, we need to configure below property in hibernate configuration file.

<property name="hibernate.cache.use_query_cache">true</property>

And in code, we need to use the etCacheable(true) method of Query, quick example looks like below.

Query query = session.createQuery("from Employee"); query.setCacheable(true); query.setCacheRegion("ALL_EMP");

28. What is the benefit of Hibernate Criteria API?
Hibernate provides Criteria API that is more object oriented for querying the database and getting results. We can’t use Criteria to run update or delete queries or any DDL statements. It’s only used to fetch the results from the database using more object oriented approach.

Some of the common usage of Criteria API are:

• Criteria API provides Projection that we can use for aggregate functions such as sum(), min(), max() etc.
• Criteria API can be used with ProjectionList to fetch selected columns only.
• Criteria API can be used for join queries by joining multiple tables, useful methods are createAlias(), setFetchMode() and setProjection()
• Criteria API can be used for fetching results with conditions, useful methods are add() where we can add Restrictions.
• Criteria API provides addOrder() method that we can use for ordering the results.

29. What is the default cache service of hibernate?
Hibernate supports multiple cache services like EHCache, OSCache, SWARMCache and TreeCache and default cache service of hibernate is EHCache.

30. What is transient instance state in Hibernate?
If an instance is not associated with any persistent context and also, it has never been associated with any persistent context, then it's said to be in transient state.

31. What the four ORM levels are in hibernate?
Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping

32. What the two methods are of hibernate configuration?
We can use any of the following two methods of hibernate configuration:
a. XML based configuration ( using hibernate.cfg.xml file)
b. Programmatic configuration ( Using code logic)

33. What's general hibernate flow using RDBMS?
General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.

34. What's Hibernate?
Hibernate is a popular framework of Java which allows an efficient Object Relational mapping using configuration files in XML format. After java objects mapping to database tables, database is used and handled using Java objects without writing complex database queries.

Hibernate is an ORM (Object Relational Mapping) and persistent framework. The framework helps to map plain java object to relational database table using xml configuration file.

The framework helps to perform following things.

? Perform basic CURD operations.

? Write queries referring to java classes (HQL queries).

? Facilities to specify metadata.

? Dirty checking, lazy association fetching.

35. What's HQL?
HQL is the query language used in Hibernate which is an extension of SQL. HQL is very efficient, simple and flexible query language to do various type of operations on relational database without writing complex database queries.

36. What's the difference between load() and get() method in hibernate?
Load() methods results in an exception if the required records isn't found in the database while get() method returns null when records against the id isn't found in the database. So, ideally we should use Load() method only when we are sure about existence of records against an id.

37. What's the difference between session.save() and session.saveOrUpdate() methods in hibernate?
Sessionsave() method saves a record only if it's unique with respect to its primary key and will fail to insert if primary key already exists in the table. saveOrUpdate() method inserts a new record if primary key is unique and will update an existing record if primary key exists in the table already.

38. What's the usage of Configuration Interface in hibernate?
Configuration interface of hibernate framework is used to configure hibernate. It's also used to bootstrap hibernate. Mapping documents of hibernate are located using this interface.

39. What's the use of session.lock() in hibernate?
session.lock() method of session class is used to reattach an object which has been detached earlier. This method of reattaching doesn't check for any data synchronization in database while reattaching the object and hence may lead to lack of synchronization in data.