Hibernate Interview Questions and Answers
Last updated on 07th Oct 2020, Blog, Interview Question
If you’re looking for Hibernate Interview Questions for Experienced or Freshers, you are at right place. There are lot of opportunities from many reputed companies in the world. According to research Hibernate has a market share of about $106,013 pa. So, You still have opportunity to move ahead in your career in Hibernate Developer. Mindmajix offers Advanced Hibernate Interview Questions 2020 that helps you in cracking your interview & acquire dream career as Hibernate Developer.
1. What is Hibernate?
Hibernate is one of the most popular Java frameworks that simplify the development of Java applications to interact with the database. It is an Object-relational mapping (ORM) tool. Hibernate also provides a reference implementation of Java API.It is referred as a framework which comes with an abstraction layer and also handles the implementations internally. The implementations include tasks like writing a query for CRUD operations or establishing a connection with the databases, etc.Hibernate develops persistence logic, which stores and processes the data for longer use. It is a lightweight tool and most importantly open-sourced which gives it an edge over other frameworks.
2. What are the major advantages of Hibernate Framework?
- It is open-sourced and lightweight.
- Performance of Hibernate is very fast.
- Helps in generating database independent queries.
- Provides facilities to automatically create a table.
3. What are the advantages of using Hibernate over JDBC?
Major advantages of using Hibernate over JDBC are:
- Hibernate eliminates a lot of boiler-plate code that comes with JDBC API, the code looks cleaner and readable.
- This Java framework supports inheritance, associations, and collections. These features are actually not present in JDBC.
- HQL (Hibernate Query Language) is more object-oriented and close to Java. But for JDBC, you need to write native SQL queries.
- Hibernate implicitly provides transaction management whereas, in JDBC API, you need to write code for transaction management using commit and rollback.
- JDBC throws SQLException that is a checked exception, so you have to write a lot of try-catch block code. Hibernate wraps JDBC exceptions and throws JDBCException or HibernateException which are the unchecked exceptions, so you don’t have to write code to handle it has built-in transaction management which helps in removing the usage of try-catch blocks.
4. What is an ORM tool?
It is basically a technique that maps the object that is stored in the database. An ORM tool helps in simplifying data creation, manipulation, and access. It internally uses the Java API to interact with the databases.
5. Why use Hibernate Framework?
Hibernate overcomes the shortcomings of other technologies like JDBC.
- It overcomes the database dependency faced in the JDBC.
- Changing of the databases cost a lot working on JDBC, hibernate overcomes this problem with flying colors.
- Code portability is not an option while working on JDBC. This is easily handled by Hibernate.
- Hibernate strengthens the object level relationship.
- It overcomes the exception-handling part which is mandatory while working on JDBC.
- It reduces the length of code with increased readability by overcoming the boilerplate problem.
6. What are the different functionalities supported by Hibernate?
- Hibernate is an ORM tool.
- Hibernate uses Hibernate Query Language(HQL) which makes it database-independent.
- It supports auto DDL operations.
- This Java framework also has an Auto Primary Key Generation support.
- Supports cache memory.
- Exception handling is not mandatory in the case of Hibernate.
7. What are the technologies that are supported by Hibernate?
Hibernate supports a variety of technologies, like:
- XDoclet Spring
- Eclipse Plug-ins
8. What is HQL?
HQL is the acronym of Hibernate Query Language. It is an Object-Oriented Query Language and is independent of the database.
9. How to achieve mapping in Hibernate?
Association mappings are one of the key features of Hibernate. It supports the same associations as the relational database model. They are:
- One-to-One associations
- Many-to-One associations
- Many-to-Many associations
You can map each of them as a uni- or bidirectional association.
10. Name some of the important interfaces of Hibernate framework?
Hibernate interfaces are:
- SessionFactory (org.hibernate.SessionFactory)
- Session (org.hibernate.Session)
- Transaction (org.hibernate.Transaction)
11. What is One-to-One association in Hibernate?
In this type of mapping, you only need to model the system for the entity for which you want to navigate the relationship in your query or domain model. You need an entity attribute that represents the association, so annotate it with an @OneToOne annotation.
12. What is One-to-Many association in Hibernate?
In this type of association, one object can be associated with multiple/different objects. Talking about the mapping, the One-to-Many mapping is implemented using a Set Java collection that does not have any redundant element. This One-to-Many element of the set indicates the relation of one object to multiple objects.
13. What is Many-to-Many association in Hibernate?
Many-to-Many mapping requires an entity attribute and a @ManyToMany annotation. It can either be unidirectional and bidirectional. In Unidirectional, the attributes model the association and you can use it to navigate it in your domain model or JPQL queries. The annotation tells Hibernate to map a Many-to-Many association. The bidirectional relationship mapping allows you to navigate the association in both directions.
14. How to integrate Hibernate and Spring?
Spring is also one of the most commonly used Java frameworks in the market today. Spring is a JavaEE Framework and Hibernate is the most popular ORM framework. This is why Spring Hibernate combination is used in a lot of enterprise applications.
Following are the steps you should follow to integrate Spring and Hibernate.
- Add Hibernate-entity manager, Hibernate-core and Spring-ORM dependencies.
- Create Model classes and corresponding DAO implementations for database operations. The DAO classes will use SessionFactory that will be injected by the Spring Bean configuration.
- Note that you don’t need to use Hibernate Transaction Management, as you can leave it to the Spring declarative transaction management using @Transactional annotation.
15. What do you mean by Hibernate Configuration File?
Hibernate Configuration File mainly contains database-specific configurations and are used to initialize SessionFactory. Some important parts of the Hibernate Configuration File are Dialect information, so that hibernate knows the database type and mapping file or class details.
Subscribe For Free Demo[contact-form-7 404 "Not Found"]
16. Mention some important annotations used for Hibernate mapping?
Hibernate supports JPA annotations. Some of the major annotations are:
- javax.persistence.Entity: This is used with model classes to specify they are entity beans.
- javax.persistence.Table: It is used with entity beans to define the corresponding table name in the database.
- javax.persistence.Access: Used to define the access type, field or property. The default value is field and if you want Hibernate to use the getter/setter methods then you need to set it to a property.
- javax.persistence.Id: Defines the primary key in the entity bean.
- javax.persistence.EmbeddedId: It defines a composite primary key in the entity bean.
- javax.persistence.Column: Helps in defining the column name in the database table.
- javax.persistence.GeneratedValue: It defines the strategy to be used for the generation of the primary key. It is also used in conjunction with javax.persistence.GenerationType enum.
17. What is Session in Hibernate and how to get it?
Hibernate Session is the interface between Java application layer and Hibernate. It is used to get a physical connection with the database. The Session object created is lightweight and designed to be instantiated each time an interaction is needed with the database. This Session provides methods to create, read, update and delete operations for a constant object. To get the Session, you can execute HQL queries, SQL native queries using the Session object.
18. What is Hibernate SessionFactory?
SessionFactory is the factory class that is used to get the Session objects. The SessionFactory is a heavyweight object so usually, it is created during application startup and kept for later use. This SessionFactory is a thread-safe object which is used by all the threads of an application. If you are using multiple databases then you would have to create multiple SessionFactory objects.
19. What is the difference between openSession and getCurrentSession?
- This getCurrentSession() method returns the session bound to the context and for this to work, you need to configure it in the Hibernate configuration file. Since this session object belongs to the context of Hibernate, it is okay if you don’t close it. Once the SessionFactory is closed, this session object gets closed.
- openSession() method helps in opening a new session. You should close this session object once you are done with all the database operations. And also, you should open a new session for each request in a multi-threaded environment.
20. What are the three states of a persistent entity at a given point in time?
Instances may exist in one of the following three states at a given point in time
- transient − A new instance of a persistent class which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate.
- persistent − You can make a transient instance persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session.
- detached − Once we close the Hibernate Session, the persistent instance will become a detached instance.
21. What are the key components of a Hibernate configuration object?
The configuration provides 2 key components, namely:
- Database Connection: This is handled by one or more configuration files.
- Class Mapping setup: It helps in creating the connection between Java classes and database tables.
22. Discuss the Collections in Hibernate
Hibernate provides the facility to persist the Collections. A Collection basically can be a List, Set, Map, Collection, Sorted Set, Sorted Map. java.util.List, java.util.Set, java.util.Collection, etc, are some of the real interface types to declare the persistent collection-value fields. Hibernate injects persistent Collections based on the type of interface. The collection instances generally behave like the types of value behavior.
23. What are the collection types in Hibernate?
There are five collection types in hibernate used for one-to-many relationship mappings.
24. What is a Hibernate Template class?
When you integrate Spring and Hibernate, Spring ORM provides two helper classes – HibernateDaoSupport and HibernateTemplate. The main reason to use them was to get two things, the Session from Hibernate and Spring Transaction Management. However, from Hibernate 3.0.1, you can use the SessionFactory getCurrentSession() method to get the current session. The major advantage of using this Template class is the exception translation but that can be achieved easily by using @Repository annotation with service classes.
25. What are the benefits of using a Hibernate template?
The following are the benefits of using this Hibernate template class:
- Automated Session closing ability.
- The interaction with the Hibernate Session is simplified.
- Exception handling is automated.
26. Which are the design patterns that are used in the Hibernate framework?
There are a few design patterns used in Hibernate Framework, namely:
- Domain Model Pattern: An object model of the domain that incorporates both behavior as well as data.
- Data Mapper: A layer of the map that moves data between objects and a database while keeping it independent of each other and the map itself.
- Proxy Pattern: It is used for lazy loading.
- Factory Pattern: Used in SessionFactory.
27. Define Hibernate Validator Framework
28. What is Dirty Checking in Hibernate?
Hibernate incorporates a Dirty Checking feature that permits developers and users to avoid time-consuming write actions. This Dirty Checking feature changes or updates fields that need to be changed or updated, while keeping the remaining fields untouched and unchanged.
29. How can you share your views on mapping description files?
- Mapping description files are used by Hibernate to configure functions.
- These files have the *.hbm extension, which facilitates the mapping between database tables and Java class.
- Whether to use mapping description files or not this entirely depends on business entities.
30. What is meant by Light Object Mapping?
This means that the syntax is hidden from the business logic using specific design patterns. This is one of the valuable levels of ORM quality and this Light Object Mapping approach can be successful in cases of applications where there are very few entities, or for applications having data models that are metadata-driven.
31. What is ORM?
ORM is an acronym for Object/Relational mapping. It is a programming strategy to map objects with the data stored in the database. It simplifies data creation, data manipulation, and data access.
32. What are the core interfaces of Hibernate?
The core interfaces of Hibernate framework are:
33. Mention some of the advantages of using ORM over JDBC.
ORM has the following advantages over JDBC:
- Application development is fast.
- Management of transactions.
- Generates keys automatically.
- Details of SQL queries are hidden.
34. Define criteria in terms of Hibernate.
The objects of criteria are used for the creation and execution of the object-oriented criteria queries.
35. List some of the databases supported by Hibernate.
Some of the databases supported by Hibernate are:
- Sybase SQL Server
- Informix Dynamic Server
Get On-Demand Hibernate Course to Enhance Your Career
- Instructor-led Sessions
- Real-life Case Studies
36. List the key components of Hibernate.
Key components of Hibernate are:
37. Mention two components of the Hibernate configuration object.
- Database Connection
- Class Mapping Setup
38. How is SQL query created in Hibernate?
The SQL query is created with the help of the following syntax:
39. What is lazy loading in hibernate?
- Lazy loading in hibernate improves the performance. It loads the child objects on demand.
- Since Hibernate 3, lazy loading is enabled by default, and you don’t need to do lazy=”true”. It means not to load the child objects when the parent is loaded.
40. Is it possible to perform collection mapping with One-to-One and Many-to-One?
No, collection mapping can only be performed with One-to-Many and Many-to-Many.
41. How many types of association mapping are possible in hibernate?
There can be 4 types of association mapping in hibernate.
- One to One
- One to Many
- Many to One
- Many to Many
42. How to make an immutable class in hibernate?
If you mark a class as mutable=”false”, the class will be treated as an immutable class. By default, it is mutable=”true”.
43. What are the inheritance mapping strategies?
There are 3 ways of inheritance mapping in hibernate.
- Table per hierarchy
- Table per concrete class
- Table per subclass
- Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is a java based ORM tool that provides a framework for mapping application domain objects to the relational database tables and vice versa.
- Hibernate provides a reference implementation of Java Persistence API, that makes it a great choice as an ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. Hibernate framework provides an option to map plain old java objects to traditional database tables with the use of JPA annotations as well as XML based configuration.
44. What is Java Persistence API (JPA)?
- Java Persistence API (JPA) provides specification for managing the relational data in applications. Current JPA version 2.1 was started in July 2011 as JSR 338. JPA 2.1 was approved as final on 22 May 2013.
- JPA specifications are defined with annotations in the javax.persistence package. Using JPA annotation helps us in writing implementation independent code.
45. What are the important benefits of using Hibernate Framework?
Some of the important benefits of using hibernate framework are:
- Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care of managing resources, so we can focus on business logic.
- Hibernate framework provides support for XML as well as JPA annotations, which makes our code implementation independent.
- Hibernate provides a powerful query language (HQL) that is similar to SQL. However, HQL is fully object-oriented and understands concepts like inheritance, polymorphism and association.
- Hibernate is an open source project from Red Hat Community and used worldwide. This makes it a better choice than others because the learning curve is small and there are tons of online documentations and help is easily available in forums.
- Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that Spring Framework provides built-in support for integrating hibernate with Spring applications.
- Hibernate supports lazy initialization using proxy objects and performs actual database queries only when it’s required.
- Hibernate cache helps us in getting better performance.
- For database vendor specific features, hibernate is suitable because we can also execute native sql queries.
46. What are the advantages of Hibernate over JDBC?
Some of the important advantages of Hibernate framework over JDBC are:
- Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more cleaner and readable.
- Hibernate supports inheritance, associations and collections. These features are not present with JDBC API.
- Hibernate implicitly provides transaction management, in fact most of the queries can’t be executed outside transaction. In JDBC API, we need to write code for transaction management using commit and rollback. Read more aJDBC Transaction Management.
- JDBC API throws SQLException that is a checked exception, so we need to write a lot of try-catch block code. Most of the times it’s redundant in every JDBC call and used for transaction management. Hibernate wraps JDBC exceptions and throws JDBCException or HibernateException unchecked exceptions, so we don’t need to write code to handle it. Hibernate built-in transaction management removes the usage of try-catch blocks.
- Hibernate Query Language (HQL) is more object oriented and close to java programming language. For JDBC, we need to write native sql queries.
- Hibernate supports caching that is better for performance, JDBC queries are not cached hence performance is low.
- Hibernate provides an option through which we can create database tables too, for JDBC tables must exist in the database.
- Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for connection pool. This is a very important feature in enterprise applications and completely missing in JDBC API.
- Hibernate supports JPA annotations, so code is independent of implementation and easily replaceable with other ORM tools. JDBC code is very tightly coupled with the application.
47. Name some important interfaces of Hibernate framework?
Some of the important interfaces of Hibernate framework are:
- SessionFactory (org.hibernate.SessionFactory): 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 (org.hibernate.Session): 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 the 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 provides methods for CRUD operations.
- Transaction (org.hibernate.Transaction): 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 org.hibernate.Session might span multiple org.hibernate.Transaction in some cases.
48. What is a 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 a hibernate configuration file is Dialect information, so that hibernate knows the database type and mapping file or class details.
49. What is a 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 files come handy when we are using third party classes and we can’t use annotations.
50. 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 provides methods to get the Class metadata and Statistics instance to get the stats of query executions, second level cache details etc.
51. 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.
Best JOB Oriented Hibernate Certification Course from Real-Time ExpertsWeekday / Weekend BatchesSee Batch Details
52. What is a 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 provides 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.
53. 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.
54. What is the difference between the Hibernate Session get() and load() method?
Hibernate session comes with different methods to load data from the database. get and load are most used methods, at first look they seem similar but there are some differences between them.
- 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 loud() is better because it supports lazy loading.
- Since load() throws an exception when data is not found, we should use it only when we know data exists.
- We should use get() when we want to make sure data exists in the database.
55. 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.
56. 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 a 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()
57. What is the use of Hibernate Session merge() call?
Hibernate merge can be used to update existing values, however this method creates a copy from the passed entity object and returns it. The returned object is part of persistent context and tracked for any changes, the passed object is not tracked.
58. What is the difference between Hibernate save(), saveOrUpdate() and persist() methods?
- Hibernate save can be used to save entities to the 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 persistence is similar to saving with a 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, an update query is executed. We can use saveOrUpdate() without transaction also, but again you will face issues with mapped objects not getting saved if the session is not flushed.
59. What will happen if we don’t have a no-args constructor in Entity bean?
Hibernate uses Reflection API to create instances 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 don’t have a no-args constructor in entity beans, hibernate will fail to instantiate it and you will get a HibernateException.
60. 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.
61. Why should we not make Entity Class final?
Hibernate uses 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.
62. 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.
63. 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 create 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.
64. 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, meaning once defined it can be used throughout the application.
- However one of the major disadvantages of Named queries is that it’s hard to debug, because we need to find out the location where it’s defined.
65. 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 a 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.
66. What is Hibernate Proxy and how it helps in lazy loading?
Hibernate uses a 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.
67. 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 rolls back the transaction.
68. What is the 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 the 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 the above spring mvc example. This is a trick question to judge your knowledge and whether you are aware of recent developments or not.
69. What is Hibernate Validator Framework?
- Validation is a cross cutting task, so we should try to keep it apart from our business logic. That’s why JSR303 and JSR349 provide specifications for validating a bean by using annotations. Hibernate Validator provides the reference implementation of both these bean validation specs
70. What is the benefit of Hibernate Tools Eclipse plugin?
Hibernate Tools plugin helps us in writing hibernate configuration and mapping files easily. The major benefit is the content assist to help us with properties or xml tags to use. It also validates them against the Hibernate DTD files, so we know any mistakes beforehand.
71. How to write composite key mapping for hibernate?
The composite key mapping in hibernate can be written in two ways, EmbeddedId and IdClass. For a primary key to be composite, it should follow the following rules. The primary key must be public and its properties must be public or protected. The primary key class must be serializable and must define equals and hashCode. The primary key class must also be defined to represent the composite primary key. If the primary key follows these rules, then it can be mapped with composite using EmbeddedId or IdClass.
72. What is the transient state in hibernate ?
Hibernate objects support multiple states. Transient state is one of them, an object with the transient state will never be added to the database and it has no persistence representation in hibernate session. A Transient state object is destroyed through garbage collections after an application is closed
73. What inheritance mapping strategies are available in Hibernate?
Hibernate have 3 ways of inheritance mapping, They are
- Table per hierarchy
- Table per concrete class
- Table per subclass
74. Which annotation is used to declare a class as a hibernate bean ?
@Entity annotation is used to declare a class as an entity.
75. Explain what a dialect is?
Hibernate Dialect is used to specify the type of database we are going to use. Hibernate requires this to be known in advance so it is able to generate appropriate types of SQL statements based on database type.
76. Describe the important interfaces of Hibernate framework?
Important interfaces of Hibernate framework are:
- SessionFactory (org.hibernate.SessionFactory)
It is an immutable thread safe cache of compiled mappings for a single database.
We are supposed to initialize SessionFactory once and then we are allowed to cache and reuse it.
The SessionFactory instance is used to return the session objects for database operations.
- Session (org.hibernate.Session)
It is a single threaded and short-lived object, which represents a conversation between the persistent store and the application.
The session should be opened only when it is required and should be closed as soon as the user is done.
The session object is the interface between hibernate framework and Java application code and it provides methods for the CRUD operations.
- Transaction (org.hibernate.transaction)
It is a single threaded and short-lived object used by the application, which specifies atomic units of work.
The application is abstracted from the underlying JDBC or JTA transaction.
77. Explain the important benefits of the Hibernate framework?
Few important benefits of Hibernate framework are:
- Hibernates allows us to focus on business logic, eliminating all the boiler-plate code that comes with JDBC and handles the resources.
- Code implementation becomes independent as Hibernate framework provides the support for XML and also to the JPA annotations.
- HQL is a powerful Query Language which is similar to SQL, and HQL understands the concepts of polymorphism, inheritance, and association, which makes it fully object-oriented.
- Better performance can be achieved by Hibernate cache.
- It supports Lazy initialization with the use of proxy objects and when required performs actual database queries.
- We can execute native SQL queries using hibernate for vendor specific features.
On the whole, hibernate makes it a better choice in the current market for ORM tool, as it contains all the features that you will require in an ORM tool
78. Describe the method used to create an HQL Query and SQL Query?
Session.createQuery is used to create a new instance of a query for the HQL query string. Session.createSQLQuery is used to create a new instance of a query for the SQL query string.
79. Explain some of the elements of hbm.xml?
- It is used to define specific mappings from Java classes to database tables.
- It is used to define the mapping of unique ID attributes in class to the primary key of the database table.
- It is used to generate the primary key values automatically.
- It is used to map a Java class property to a column in the database table.
- It is used to map a java.util.set, java.util.Sortedset property in hibernate.
- It is used to map a java.util.List property in hibernate.
- It is used to map a java.util.Collection property in hibernate.
- It is used to map a java.util.Map property in hibernate
80. Explain the persistent classes in Hibernate?
In hibernate, the Java classes whose instances and objects are stored in database classes are called persistent classes
81. What are concurrency strategies?
The concurrency strategies are the mediators who are responsible for storing items and retrieving them from the cache.In case of enabling a second level cache, the developer must decide for each persistent class and collection, and also which cache concurrency, has to be implemented.
Following are the concurrency strategies that can be implemented by the developer:
- Transactional: This strategy is used mostly to read data where the prevention of stale data is critical in concurrent transactions, in the unique case of an update.
- Read- Only: This strategy is compatible with the data that can’t be modified. We can use it for reference data only.
- Read-Write: It is similar to transactional strategy. where we read mostly data and prevention of stale data is critical.
- Nonstrict-Read-Write: This strategy assures no guarantee of consistency between the database and cache. We can use this strategy only if the data can be modified and a small likelihood of stale data is not the critical concern.
82. Explain Hibernate configuration file and Hibernate mapping file?
Hibernate configuration file:
- It contains database specific configurations and is used to initialize SessionFactory.
- It provides database credentials or JNDI resource information in the hibernate configuration XML file.
- Dialect information is another important part of the hibernate configuration file.
Hibernate Mapping file:
- It is used to define the database table column mappings and entity bean fields.
- We use JPA annotations for mappings, but when we are using the third party classes sometimes XML mapping files become handy and we cannot use annotations.
83. What is Query level cache in Hibernate?
In hibernate, a cache query can be implemented that results in sets and integrates closely with the second level cache.It is an optional feature and it requires two additional cache regions that can hold the cached query results and also the timestamps whenever a table is updated. This is useful only for the queries that run frequently holding the same parameters
84. What is a second level cache in Hibernate?
It is an optional cache. And, always the first level cache will be consulted before any attempt is performed to locate an object in the second level cache. This cache can be configured on a pre-collection and per-class basis and it is mainly responsible for caching objects across the sessions
85. What is the first level cache in Hibernate?
It is session cache and mandatory cache. It is from the first level cache through which all the requests must pass.The session object stores an object under its control before committing it to the database.
86. What is Hibernate caching?
- Hibernate caches Query data and makes the application run faster.
- If used correctly, the hibernate cache can be very useful in achieving the faster application running performance.
- The main idea lying behind the cache is reducing the number of database queries, which results in reduced throughput time of the application
87. What is the difference between get() and load() methods of session objects?
There are the following differences between get() and load() methods.
- get() returns null if no data is present whereas load throws ObjectNotFoundException exception in such case.
- get() always hits the database whereas load() method doesn’t hit the database.
- get() returns actual object whereas load() returns proxy object.
- A central feature of Hibernate, proxies, depends upon the persistent class being either non-final, or the implementation of an interface that declares all public methods.
- All classes that do not extend or implement some specialized classes and interfaces required by the EJB framework.
88. What is one-to-many association?
- In One-to-Many mapping association, an object can be associated with multiple objects. For example Employee objects relate to many Certificate objects.
- A One-to-Many mapping can be implemented using a Set java collection that does not contain any duplicate element.
- <one-to-many> element of set element indicates that one object relates to many other objects.
89. What is a one-to-one association?
- A one-to-one association is similar to many-to-one association with a difference that the column will be set as unique. For example an address object can be associated with a single employee object.
- <many-to-one> element is used to define one-to-one association. The name attribute is set to the defined variable in the parent class. The column attribute is used to set the column name in the parent table which is set to unique so that only one object can be associated with another object.
90. What is a many-to-one association?
- A many-to-one association is the most common kind of association where an Object can be associated with multiple objects. For example a same address object can be associated with multiple employee objects.
- <many-to-one> element is used to define many-to-one association. The name attribute is set to the defined variable in the parent class. The column attribute is used to set the column name in the parent table.
91. Where Object/relational mappings are defined in hibernate?
Object/relational mappings are usually defined in an XML document. This mapping file instructs Hibernate how to map the defined class or classes to the database tables. We should save the mapping document in a file with the format <classname>.hbm.xml.
Are you looking training with Right Jobs?Contact Us
- Java Spring Interview Questions and Answers
- JUnit Interview Questions and Answers
- Java Interview Questions and Answers
- Spark Java Tutorial
- Struts Interview Questions and Answers
- What is Dimension Reduction? | Know the techniques
- Difference between Data Lake vs Data Warehouse: A Complete Guide For Beginners with Best Practices
- What is Dimension Reduction? | Know the techniques
- What does the Yield keyword do and How to use Yield in python ? [ OverView ]
- Agile Sprint Planning | Everything You Need to Know