Hibernate is an open source simple ORM tool. It is a java framework that simplifies the development of java application to interact with the database. Hibernate not only takes care of the mapping from Java classes to database, but also provides data query and retrieval facilities.
Hibernate is a free and Open source Framework. It is widely used light weight ORM Tools for Java Applications. It is written in Java and is Java Virtual Machine (JVM) platform based. It is used to store, manipulate and retrieve data from the database. ORM is an acronym for Object/Relational mapping. It is a programming strategy to map object with the data stored in the database. It simplifies data creation, data manipulation and data access. Object-relational mapping or ORM is the programming technique to map application domain model objects to the relational database tables. Hibernate is java based ORM tool that provides framework for mapping application domain objects to the relational database tables and vice versa. Hibernate provides reference implementation of Java Persistence API, that makes it a great choice as ORM tool with benefits of loose coupling. We can use Hibernate persistence API for CRUD operations. 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. 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 javax.persistence package. Using JPA annotation helps us in writing implementation independent code. Some of the important benefits of using hibernate framework are: Some of the important advantages of Hibernate framework over JDBC are: 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. 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. The core interfaces of Hibernate framework are: The SessionFactory is a factory of session and client of ConnectionProvider. It holds second level cache (optional) of data. The org.hibernate.SessionFactory interface provides factory method to get the object of Session. The session object provides an interface between the application and data stored in the database. It is a short-lived object and wraps the JDBC connection. It is factory of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The org.hibernate.Session interface provides methods to insert, update and delete the object. It also provides factory methods for Transaction, Query and Criteria. There are 3 states of object (instance) in hibernate. 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. 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. An entity bean instance can exist is one of the three states. 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. There are five collection types in hibernate used for one-to-many relationship mappings. 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. 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. 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 disadvantages of Named query is that it’s hard to debug, because we need to find out the location where it’s defined. 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 is: 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. ✓ Domain Model Pattern ✓ Data Access Object (DAO) ✓ Abstract Factory ✓ Data Mapper ✓ Proxy ✓ Object-Relational Mapping (ORM) ✓ Query Object Hibernate data type plays an important role as it acts like a bridge between java types and DB data types. ✓ Primitive types ✓ Date and time types ✓ Binary and large object types ✓ Other JDK-related types Session interface: It allows you to create query objects to retrieve persistent objects. SessionFactory interface: It is a factory that delivers the session objects to hibernate application. Configuration interface: It is used to configure and bootstrap hibernate. Transaction interface: This interface abstracts the code from any kind of transaction implementations such as JDBC transaction, JTA transaction Query and Criteria interfaces: This interface allows the user to perform queries and also control the flow of the query execution. <map> element is used. java.io.Serializable. It is used to create and execute object-oriented Queries to retrieve the objects. The process of Hibernate tuning is designed to optimize Hibernate applications’ performance. The three strategies are: JPA stands for Java Persistence API. It provides specification for managing the relational data in applications. HQL stands for Hibernate Query Language. It’s very similar to SQL except that we use Objects instead of table names, that makes it closer to object-oriented programming. Both Hibernate and Java Persistence support queries written in Native SQL It 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. Transactions denote a work file which can save changes made or revert back the changes. A transaction can be started by session.beginTransaction() and it uses JDBC connection, CORBA or JTA. When this session starts several transactions may occur. These methods are the most convenient to use in hibernate. These methods allow you to load all your Hibernate documents at a time. These methods simplify code configuration, refactoring, layout, etc. These functions help you to add your hibernate mapping to Hibernate initialization files. POJO stands for plain old java objects. These are just basic JavaBeans that have defined setter and getter methods for all the properties that are there in that bean. Besides they can also have some business logic related to that property. 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. ✓ Object identity ✓ Object equality ✓ Database identity Thera are four ORM levels in hibernate. ✓ Pure Relational ✓ Light Object Mapping ✓ Medium Object Mapping ✓ Full Object Mapping Some database engines supported by Hibernate: ✓ Oracle ✓ MySQL ✓ PostgreSQL ✓ SAP DB ✓ Sybase ASE ✓ H2 Database ✓ Microsoft SQL Server Database ✓ HSQL Database Engine ✓ DB2/NT ✓ Informix Dynamic Server ✓ FrontBase @Transient is one of the Object states. In hibernate which is object relation mapping, it will map or create every variable with the class we have defined. Automatic dirty checking can be defined as a feature that helps us in saving the effort of explicitly asking Hibernate to update the database every time we modify or make changes to the state of an object inside a transaction. There are many extension interfaces provided by hibernate. ✓ ProxyFactory interface: For create proxies ✓ TransactionFactory interface: For transaction management ✓ ConnectionProvider interface: For JDBC connection management ✓ Transaction interface: For transaction management ✓ TransactionManagementLookup interface: For transaction management. ✓ Cahce interface: It provides caching techniques and strategies ✓ CacheProvider interface: same as Cache interface ✓ ClassPersister interface: It provides ORM strategies ✓ IdentifierGenerator interface: For primary key generation ✓ Dialect abstract class: It provides SQL support Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file. Three types of instance states: Transient -It is not associated with any persistence context Persistent -It is associated with a persistence context Detached -It was associated with a persistence context which has been closed –currently not associated Spring and Hibernate are two different things, Spring has several components like Dependency Injection, Spring MVC, Spring ORM, Spring Rest API. So Spring ORM and Hibernate are kind of similar, they both deal with the object relation model, which means they deal with connection java objects to database entities. Now if you want to build a Rest API using Spring, you can use the Spring Rest API (Here is the getting start guide for Spring Rest Building a RESTful Web Service) for ORM you can either choose Hibernate or Spring ORM framework in either cases there are advantages and disadvantages but major industry goes with using Hibernate (I might be wrong!!) I’ve used both of them Spring ORM is quite useful in simple scenarios and Hibernate in some complex scenarios, whereas in most complex scenarios both of them are not quite useful when you want to write really complex queries. (Both of them provide functionalities two write queries by yourself in the case of complex scenarios). Hibernate implements a cache region for queries result set that integrates closely with the hibernate second-level cache. Query Cache 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. And in code, we need to use setCacheable(true) method of Query, quick example looks like below. You can use below property for hibernate configuration to log SQL queries. There are three ways are used to disable the cache: By setting hibernate. cache. use_second_level_cache property to false By using CACHEMODE.IGNORE By Using a cache provider such as org.hibernate.cache.NoCacheProvider @Entity annotation is used to declare a class as an entity. For Example : @LazyCollection annotation is used to specify the lazy fetching behavior of a given collection. The @RowId annotation is used to specify the database column used as a ROWID pseudocolumn The @SqlFragmentAlias annotation is used to specify an alias for a Hibernate @Filter.What is hibernate?
Post a Question
What is ORM?
What is Hibernate Framework?
What is Java Persistence API (JPA)?
What are the important benefits of using Hibernate Framework?
What are the advantages of Hibernate over JDBC?
What is hibernate configuration file?
What is hibernate mapping file?
What are the core interfaces of Hibernate?
What is SessionFactory?
What is Session?
What the states of object are in hibernate?
What is Hibernate Session and how to get it?
What is hibernate caching? Explain Hibernate first level cache?
What are different states of an entity bean?
What is difference between Hibernate save(), saveOrUpdate() and persist() methods?
What are the collection types in Hibernate?
What is the benefit of native sql query support in hibernate?
What is Named SQL Query?
What are the benefits of Named SQL Query?
What is the benefit of Hibernate Criteria API?
How to integrate Hibernate and Spring frameworks?
Other Important Hibernate Interview Questions and Answers
What are the important design patterns in Hibernate Framework?
What are different data types supports in Hibernate?
What are the core Interfaces of Hibernate?
Which element is used in hibernate maps java.util.Sorted Map property?
What is the return type of save ()?
What is Criteria object in Hibernate?
What is Hibernate tuning?
What is Java Persistence API (JPA)?
What is HQL?
What is the benefit of Native SQL query support in hibernate?
What do you know about transaction file?
What is the difference between add jar() and add directory() methods?
What are POJOs?
How does hibernate code looks like?
Session session = getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
MyPersistanceClass mpc = new MyPersistanceClass (“Sample App”);
session.save(mpc);
tx.commit();
session.close();
What is difference between Hibernate save(), saveOrUpdate() and persist() methods?
What are the different methods of identifying an object?
What are the ORM levels in hibernate?
What are the databases that Hibernate supports?
What is @Transient in Hibernate?
How would you define automatic dirty checking?
What are the Extension interfaces that are there in hibernate?
How can we bind hibernate session factory to JNDI ?
What are the types of Hibernate instance states?
What is the main difference between spring and hibernate?
Can you explain Query Cache in Hibernate?
<property name="hibernate.cache.use_query_cache">true</property>
Query query = session.createQuery("from Employee");
query.setCacheable(true);
query.setCacheRegion("ALL_EMP");
which property is used to log hibernate generated sql queries in log files?
<property name="hibernate.show_sql">true</property>
How many ways are used to disable Hibernate’s second-level cache?
Which annotation is used to declare a class as a hibernate bean ?
@Entity
@Table(name="posts")
public class Post{
String title;
String description;
}
Which annotation is used to specify the lazy fetching behavior of a given collection?
Which annotation is used to specify the database column used as a ROWID pseudocolumn?
Which annotation is used to specify an alias for a Hibernate @Filter?
Name the Hibernate Annotations?
Related posts:
- Core Java Interview Questions and Answers
- Java Multithreading Interview Question and Answers
- Java Threading Interview Questions and Answers
- JAX-WS Interview Questions and Answers
- JDBC Interview Questions and Answers
- JSF Interview Questions and Answers
- Portal and Portlet Interview Questions and Answers
- Swing Interview Questions and Answers