Hibernate Interview Questions

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

What is Hibernate Framework?

Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate framework provide option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration. Similarly hibernate configurations are flexible and can be done from XML configuration file as well as programmatically.

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.

What are the benefits of ORM and Hibernate?

*Productivity* - Hibernate reduces the burden of developer by providing much of the functionality and lets the developer concentrate on business logic. *Maintainability* - As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC. *Performance* - Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance. **Vendor independence - Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

What does ORM consist of?

- It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes - Should have a language or an API for specifying queries that refer to the classes and the properties of classes - An ability for specifying mapping metadata - It should have a technique for ORM implementation to interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions

What are the four ORM levels in hibernate?

- Pure relational (stored procedure) - Light objects mapping (JDBC) - Medium objects mapping - Full object mapping (includes inheritance, polymorphism, composition)

What are the important benefits of using Hibernate Framework?

- eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources - provides support for XML as well as JPA annotations - provides HQL: a fully object-oriented query lg that understands concepts like inheritance, polymorphism and association. - is an open source project that is used worldwide => the learning curve is small and there are tons of online documentations and help is easily available in forums. - it is easy to integrate with other Java EE frameworks (Spring Framework provides built-in support for integrating hibernate with Spring applications.) - supports lazy initialization using proxy objects and perform actual database queries only when it's required. - its cache helps us in getting better performance. - for database vendor specific feature, hibernate is suitable because we can also execute native sql queries.

Name some important annotations used for Hibernate mapping? (at least 5)

- 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.Column: Used to define the column name in database table. - 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

General flow of Hibernate communication with the RDBMS?

1. Load the config file and create config object. 2. Create session factory from config object 3. Get one session from the factory 4. Create HQL Query 5. Execute query

What is the main difference between the Set and Bag collections in Hibernate?

A <bag> is an unordered collection, which can contain duplicated elements. That means if you persist a bag with some order of elements, you cannot expect the same order retains when the collection is retrieved. There is not a "bag" concept in Java collections framework, so we just use a java.util.List corresponds to a <bag>. A <set> is similar to <bag> except that it can only store unique objects. That means no duplicate elements can be contained in a set. When you add the same element to a set for second time, it will replace the old one. A set is unordered by default but we can ask it to be sorted. The corresponding type of a in Java is java.util.Set.

What is connection pooling?

A cache of database connections maintained so that the connections can be reused for when requests to the database are required.

What are the essential properties of a transaction?

ACID: - *Atomicity* - a transaction either is successfully executed or it never happened - *Consistency* - ensures that the transaction will bring the db from one valid state to another - *Isolation* - a transaction is treated as if it is the only one performing CRUD operations in the db - *Durability* - ensured that the data is not lost during system crashes

How to integrate Hibernate and Spring frameworks?

Add hibernate-entitymanager, 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 or org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean in Spring Bean configuration file. For Hibernate 4, there is single class org.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.

What are different states of an entity bean?

An entity bean instance can exist is one of the three states. Transient: When an object is never persisted or associated with any session, it's in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete(). Persistent: When an object is associated with a unique session, it's in persistent state. Any instance returned by a get() or load() method is persistent. Detached: When an object is previously persistent but not associated with any session, it's in detached state. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().

How do you define sequence generated primary key?

By using the <generator> tag or @GeneratedValue

What Is a First-Level Cache?

As most other fully-equipped ORM frameworks, Hibernate has the concept of first-level cache. It is a session scoped cache which ensures that each entity instance is loaded only once in the persistent context. Once the session is closed, first-level cache is terminated as well. This is actually desirable, as it allows for concurrent sessions to work with entity instances in isolation from each other.

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.

What's the usage of callback interfaces in hibernate?

Callback interfaces of hibernate are useful in receiving event notifications from objects. For example, when an object is loaded or deleted, an event is generated and notification is sent using callback interfaces.

How do you setup and use hibernate?

Create Java application, mavenize it, add hibernate dependencies. The most important thing is the hibernate.cfg.xml file. You must add session-factory tag and add properties for connection driver, url, username, password, the hibernate dialect, ddl schema, mapping resource or mapping class.

Name some second level caching:

EhCache, JBoss

What is the difference between the first and second level caches in Hibernate?

First level cache it is the default cache and it is formed by the session object. This cache is only available in a single session. Second level cache is optional and it is formed by the session factory object. This cache is available to multiple sessions.

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>

What is meant by full object mapping?

Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and caching strategies are implemented transparently to the application.

How to integrate log4j logging in hibernate application?

Hibernate 4 uses JBoss logging rather than slf4j used in earlier versions. For log4j configuration, we need to follow below steps. Add log4j dependencies for maven project, if not maven then add corresponding jar files. Create log4j.xml configuration file or log4j.properties file and keep it in the classpath. You can keep file name whatever you want because we will load it in next step. For standalone projects, use static block to configure log4j using DOMConfigurator or PropertyConfigurator. For web applications, you can use ServletContextListener to configure it. That's it, our setup is ready. Create org.apache.log4j.Logger instance in the java classes and start logging.

What is HQL and what are it's benefits?

Hibernate Framework comes with a powerful object-oriented query language - Hibernate Query Language (HQL). It's very similar to SQL except that we use Objects instead of table names, that makes it more close to object oriented programming. Hibernate query language is case-insensitive except for java class and variable names. So SeLeCT is the same as sELEct is the same as SELECT, but com.journaldev.model.Employee is not same as com.journaldev.model.EMPLOYEE. The HQL queries are cached but we should avoid it as much as possible, otherwise we will have to take care of associations. However it's a better choice than native sql query because of Object-Oriented approach. Read more at HQL Example.

What are the benefits of Named SQL Query?

Hibernate Named Query helps us in grouping queries at a central location rather than letting them scattered all over the code. Hibernate Named Query syntax is checked when the hibernate session factory is created, thus making the application fail fast in case of any error in the named queries. Hibernate Named Query is global, means once defined it can be used throughout the application. However one of the major disadvantage of Named query is that it's hard to debug, because we need to find out the location where it's defined.

What is Hibernate Session and how to get it?

Hibernate Session is the interface between java application layer and hibernate. This is the core interface used to perform database operations. Lifecycle of a session is bound by the beginning and end of a transaction. Session provide methods to perform create, read, update and delete operations for a persistent object. We can execute HQL queries, SQL native queries and create criteria using Session object.

Hibernate Session is thread safe?

Hibernate Session object is not thread safe, every thread should get it's own session instance and close it after it's work is finished.

What is difference between openSession and getCurrentSession?

Hibernate SessionFactory getCurrentSession() method returns the session bound to the context. But for this to work, we need to configure it in hibernate configuration file. Since this session object belongs to the hibernate context, we don't need to close it. Once the session factory is closed, this session object gets closed. <property name="hibernate.current_session_context_class">thread</property> Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.

What is hibernate configuration file?

Hibernate configuration file contains database specific configurations and used to initialize SessionFactory. We provide database credentials or JNDI resource information in the hibernate configuration xml file. Some other important parts of hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.

What is hibernate mapping file?

Hibernate mapping file is used to define the entity bean fields and database table column mappings. We know that JPA annotations can be used for mapping but sometimes XML mapping file comes handy when we are using third party classes and we can't use annotations.

What is the use of Hibernate Session merge() call?

Hibernate merge can be used to update existing values, however this method create a copy from the passed entity object and return it. The returned object is part of persistent context and tracked for any changes, passed object is not tracked.

Can we execute native sql query in hibernate?

Hibernate provide option to execute native SQL queries through the use of SQLQuery object. For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first level caching.

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.

What will happen if we don't have no-args constructor in Entity bean?

Hibernate uses Reflection API to create instance of Entity beans, usually when you call get() or load() methods. The method Class.newInstance() is used for this and it requires no-args constructor. So if you won't have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get HibernateException.

What is Named SQL Query?

Hibernate provides Named Query that we can define at a central location and use them anywhere in the code. We can created named queries for both HQL and Native SQL. Hibernate Named Queries can be defined in Hibernate mapping files or through the use of JPA annotations @NamedQuery and @NamedNativeQuery.

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.

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 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 session is not flushed.

Why we should not make Entity Class final?

Hibernate use proxy classes for lazy loading of data, only when it's needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.

What is Hibernate Proxy and how does it help in lazy loading?

Hibernate uses proxy object to support lazy loading. Basically when you load data from tables, hibernate doesn't load all the mapped objects. As soon as you reference a child or lookup object via getter methods, if the linked entity is not in the session cache, then the proxy code will go to the database and load the linked object. It uses javassist to effectively and dynamically generate sub-classed implementations of your entity objects.

What is Query Cache in Hibernate?

If you have queries that run over and over, with the same parameters, query caching provides performance gains. 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 setCacheable(true) method of Query, quick example looks like below. Query query = session.createQuery("from Employee"); query.setCacheable(true); query.setCacheRegion("ALL_EMP");

Hibernate SessionFactory is thread safe?

Internal state of SessionFactory is immutable, so it's thread safe. Multiple threads can access it simultaneously to get Session instances.

What Is a Second-Level Cache?

Its is a SessionFactory-scoped cache. When an entity instance is looked up by its id (either by application logic or by Hibernate internally, e.g. when it loads associations to that entity from other entities), and if second-level caching is enabled for that entity, the following happens: - If an instance is already present in L1 cache, it is returned from there - If an instance is not found in L1 cache, and the corresponding instance state is cached in the L2 cache, then the data is fetched from there and an instance is assembled and returned - Otherwise, the necessary data are loaded from the database and an instance is assembled and returned Once the instance is stored in the persistence context (L1 cache), it is returned from there in all subsequent calls within the same session until the session is closed or the instance is manually evicted from the persistence context. Also, the loaded instance state is stored in L2 cache if it was not there already.

What is Java Persistence API (JPA)?

Java Persistence API (JPA) provides specification for managing the relational data in applications. JPA specifications is defined with annotations in javax.persistence package. Using JPA annotation helps us in writing implementation independent code.

What is the difference in the hibernate config file between the mapped and annotation driven class?

Mapping file: <mapping resource ="myTable.hbm.xml"/> Annotated POJO: <mapping class="myTable"/>

What is the benefit of native sql query support in hibernate?

Native SQL Query comes handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.

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.

Name some important interfaces of Hibernate framework?

Session, SessionFactory, Configuration, Transaction, Query, and Criteria interface - SessionFactory is an immutable thread-safe cache of compiled mappings for a single database. We need to initialize SessionFactory once and then we can cache and reuse it. SessionFactory instance is used to get the Session objects for database operations. - Session is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It wraps JDBC java.sql.Connection and works as a factory for org.hibernate.Transaction. We should open session only when it's required and close it as soon as we are done using it. Session object is the interface between java application code and hibernate framework and provide methods for CRUD operations. - Transaction is a single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC or JTA transaction. A Session might span multiple Transactions in some cases.

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.

How do you configure an L2 cache in Hibernate?

Step 1: Include the property tag in the hibernate.cfg.xml file <property name="hibernate.cache.provider_class"> org.hibernate.cache.EhCacheProvider </property> Step 2: Create an cache properties xml file or use annotations in the persistent class

What is a meant by medium object mapping?

The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

What is a pure relational ORM?

The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

What is a meant by light object mapping?

The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

Ways to express joins in HQL

There are 4 ways of expressing inner and outer joins: 1. Implicit association join 2. Ordinary join in the FROM clause 3. Fetch join in the FROM clause 4. theta-style join in the WHERE clause

What are the collection types in Hibernate?

There are five collection types in hibernate used for one-to-many relationship mappings. Bag Set List Array Map

How to implement Joins in Hibernate?

There are various ways to implement joins in hibernate. Using associations such as one-to-one, one-to-many etc. Using JOIN in the HQL query. There is another form "join fetch" to load associated data simultaneously, no lazy loading. We can fire native sql query and use join keyword.

What is N+1 SELECT query issue? And what is the solution in Hibernate?

There exists a one-to-many relationship inside an object. A naive O/R implementation would SELECT all primary objects and then do N additional SELECTs for getting the secondary information of each primary object. As you see, the N+1 problem can happen if the first query populates the primary object and the second query populates all the child objects for each of the unique primary objects returned. Resolve N+1 SELECTs problem: (i) HQL fetch join "from MobileVendor mobileVendor join fetch mobileVendor.phoneModel PhoneModels" Corresponding SQL would be (assuming tables as follows: t_mobile_vendor for MobileVendor and t_phone_model for PhoneModel) SELECT * FROM t_mobile_vendor vendor LEFT OUTER JOIN t_phone_model model ON model.vendor_id=vendor.vendor_id (ii) Criteria query Criteria criteria = session.createCriteria(MobileVendor.class); criteria.setFetchMode("phoneModels", FetchMode.EAGER); In both cases, our query returns a list of MobileVendor objects with the phoneModels initialized. Only one query needs to be run to return all the PhoneModel and MobileVendor information required.

How transaction management works in Hibernate?

Transaction management is very easy in hibernate because most of the operations are not permitted outside of a transaction. So after getting the session from SessionFactory, we can call session beginTransaction() to start the transaction. This method returns the Transaction reference that we can use later on to either commit or rollback the transaction. Overall hibernate transaction management is better than JDBC transaction management because we don't need to rely on exceptions for rollback. Any exception thrown by session methods automatically rollback the transaction.

What is the difference between the update and merge methods?

Update means to edit something, it should be used if a session does not contain an already persistent state with same id Should be used inside the session only Merge means to combine something, it should be used if you do not know the state of the session

How can we get hibernate statistics?

We can get hibernate statistics using getStatistics() method of SessionFactory class as shown below: SessionFactory.getStatistics()

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.

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

What is 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, read more at java object list sorting. 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(); Ordered list is better than sorted list because the actual sorting is done at database level, that is fast and doesn't cause memory issues.

What is difference between Hibernate Session get() and load() method?

get() loads the data as soon as it's called whereas load() returns a proxy object and loads data only when it's actually required, so load() is better because it support lazy loading. load() - faster - lazy loading - used when it is sure that the record exists - throws an exception if the record is not found - Load method does not hit the database get() - slower - used when it is not sure if the record exists - returns null if the record is not found - always hits the database

2 ways of initializing the factory

new AnnotationConfiguration.configure.buildSessionFactory() new Configuration().configure().buildSessionFactory()

What is the difference between persist() and merge() in Hibernate?

persist(entity) should be used with totally new entities, to add them to DB (if entity already exists in DB there will be EntityExistsException throw). merge(entity) should be used, to put entity back to persistence context if the entity was detached and was changed.


Ensembles d'études connexes

Marketing Research Exam #2 Review

View Set

Slope-Intercept, Standard, and Point-Slope Form

View Set

Description and Function of Parts of the Human Eye

View Set

Cardiac Arrhythmias/disturbances

View Set

Chapter 13 - Physical Assessment

View Set

MGB homework answers for Final Exam

View Set

Ch. 4, 5, 6--Infection control & sterilization

View Set