Hibernate Interview Questions and Answers.Hibernate is one of the most widely used ORM tool for Java applications.Its used a lot in enterprise applications for database operations.So I decided to write a post about hibernate interview questions to brush up your knowledge before the interview.Whether you are fresher or experienced, having good knowledge or Hibernate ORM tool helps in cracking interview.Here I am providing important hibernate interview questions with answers to help you brush up your knowledge and impress your interviewer.Just like other interview questions posts, chances are that I will be adding more questions to this list in future, so you might want to bookmark it for future reference.Recently I have written a lot of posts on hibernate, most of them contains complete downloadable projects.I will provide reference to them as and when needed and you can go through them to refresh your knowledge.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 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.Hibernate Update Sql Query Example To Find' title='Hibernate Update Sql Query Example To Find' />the significant prevalence of SQL Injection vulnerabilities, and the attractiveness of the target i.Hibernate Update Sql Query Example To Find' title='Hibernate Update Sql Query Example To Find' />In this excerpt from Manning Publications Hibernate in Action, authors Christian Bauer and Gavin King introduce Hibernates core APIs and explain its basic.Hibernate first program hibernate hello world program, how to use hibernate insert command,insert query in hibernate, how to use hibernate insert query.Similarly hibernate configurations are flexible and can be done from XML configuration file as well as programmatically.For a quick overview of hibernate framework usage, you can go through Hibernate Beginners Tutorial.What is Java Persistence API JPA Java Persistence API JPA provides specification for managing the relational data in applications.Current JPA version 2.July 2.JSR 3.JPA 2. 1 was approved as final on 2.May 2.JPA specifications is defined with annotations in javax.Using JPA annotation helps us in writing implementation independent code.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, that 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 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, its so popular that Spring Framework provides built in support for integrating hibernate with Spring applications.Hibernate supports lazy initialization using proxy objects and perform actual database queries only when its required.Hibernate cache helps us in getting better performance.For database vendor specific feature, hibernate is suitable because we can also execute native sql queries.Overall hibernate is the best choice in current market for ORM tool, it contains all the features that you will ever need in an ORM tool.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 cant be executed outside transaction.In JDBC API, we need to write code for transaction management using commit and rollback.Read more at JDBC 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 its redundant in every JDBC call and used for transaction management.Hibernate wraps JDBC exceptions and throw JDBCException or Hibernate.Exception un checked exception, so we dont 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 provide 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 Data.Source for connection pool.This is very important feature in enterprise application 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.Name some important interfaces of Hibernate framework Some of the important interfaces of Hibernate framework are Session.Factory org.Session. Factory Session.Factory is an immutable thread safe cache of compiled mappings for a single database.We need to initialize Session.Factory once and then we can cache and reuse it.Session.Factory instance is used to get the Session objects for database operations.Session org.Session Session is a single threaded, short lived object representing a conversation between the application and the persistent store.It wraps JDBC java.Connection and works as a factory for org.Transaction.We should open session only when its 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 org.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.Session might span multiple org.Transaction in some cases.What is hibernate configuration file Hibernate configuration file contains database specific configurations and used to initialize Session.Factory.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 cant use annotations.Name some important annotations used for Hibernate mapping Hibernate supports JPA annotations and it has some other annotations in org.Some of the important JPA and hibernate annotations used are javax.Entity Used with model classes to specify that they are entity beans.Table Used with entity beans to define the corresponding table name in database.Access Used to define the access type, either field or property.Default value is field and if you want hibernate to use gettersetter methods then you need to set it to property.Id Used to define the primary key in the entity bean.Embedded. Canon Rebel T4i Software Download there. Id Used to define composite primary key in the entity bean.Column Used to define the column name in database table.Generated.Value Used to define the strategy to be used for generation of primary key.Used in conjunction with javax.Generation.Type enum.One. To.One Used to define the one to one mapping between two entity beans.We have other similar annotations as One.To.Many, Many. To.One and Many.To.Manyorg. hibernate.Cascade Used to define the cascading between two entity beans, used with mappings.It works in conjunction with org.Cascade.Typejavax.Primary.Key. Join.Column Used to define the property for foreign key.Used with org.Generic. Generator and org.Transactions and concurrency HibernateIn this topic, we finally talk about transactions and how you create and control units of work in a application.Well show you how transactions work at the lowest level the database and how you work with transactions in an application that is based on native Hibernate, on Java Persistence, and with or without Enterprise Java.Beans.Transactions allow you to set the boundaries of a unit of work an atomic group of operations.They also help you isolate one unit of work from another unit of work in a multiuser application.We talk about concurrency and how you can control concurrent data access in your application with pessimistic and optimistic strategies.Finally, we look at nontransactional data access and when you should work with your database in autocommit mode.Transaction essentials Lets start with some background information.Application functionality requires that several things be done at the same time.For example, when an auction finishes, three different tasks have to be performed by the Caveat.Emptor application 1 Mark the winning highest amount bid.Charge the seller the cost of the auction.Notify the seller and successful bidder.What happens if you cant bill the auction costs because of a failure in the external credit card system The business requirements may state that either all listed actions must succeed or none must succeed.If so, you call these steps collectively a transaction or unit of work.If only one step fails, the whole unit of work must fail.This is known as atomicity, the notion that all operations are executed as an atomic unit.Furthermore, transactions allow multiple users to work concurrently with the same data without compromising the integrity and correctness of the data a particular transaction should not be visible to other concurrently running transactions.Several strategies are important to fully understand this isolation behavior, and well explore them in this topic.Transactions have other important attributes, such as consistency and durability.Consistency means that a transaction works on a consistent set of data a set of data that is hidden from other concurrently running transactions and that is left in a clean and consistent state after the transactions completes.Your database integrity rules guarantee consistency.You also want correctness of a transaction.For example, the business rules dictate that the seller is charged once, not twice.This is a reasonable assumption, but you may not be able to express it with database constraints.Hence, the correctness of a transaction is the responsibility of the application, whereas consistency is the responsibility of the database.Durability means that once a transaction completes, all changes made during that transaction become persistent and arent lost even if the system subsequently fails.Together, these transaction attributes are known as the ACID criteria.Database transactions have to be short.A single transaction usually involves only a single batch of database operations.In practice, you also need a concept that allows you to have long running conversations, where an atomic group of database operations occur in not one but several batches.Conversations allow the user of your application to have think time, while still guaranteeing atomic, isolated, and consistent behavior.Now that weve defined our terms, we can talk about transaction demarcation and how you can define the boundaries of a unit of work.Database and system transactions Databases implement the notion of a unit of work as a database transaction.A database transaction groups data access operationsthat is, SQL operations.All SQL statements execute inside a transaction there is no way to send an SQL statement to a database outside of a database transaction.A transaction is guaranteed to end in one of two ways Its either completely committed or completely rolled back.Hence, we say database transactions are atomic.In figure 1.To execute all your database operations inside a transaction, you have to mark the boundaries of that unit of work.You must start the transaction and at some point, commit the changes.If an error occurs either while executing operations or when committing the transaction, you have to roll back the transaction to leave the data in a consistent state.This is known as transaction demarcation and, depending on the technique you use, involves more or less manual intervention.Figure 1.Lifecycle of an atomic unit of worka transaction.In general, transaction boundaries that begin and end a transaction can be set either programmatically in application code or declaratively.Download Adobe Flash Player For Samsung Omnia 2 Specifications more.Programmatic transaction demarcation In a nonmanaged environment, the JDBC API is used to mark transaction boundaries.You begin a transaction by calling set.Auto.Commitfalse on a JDBC Connection and end it by calling commit.You may, at any time, force an immediate rollback by calling rollback.In a system that manipulates data in several databases, a particular unit of work involves access to more than one resource.In this case, you cant achieve atomicity with JDBC alone.You need a transaction manager that can handle several resources in one system transaction.Such transaction processing systems expose the Java Transaction API JTA for interaction with the developer.The main API in JTA is the User.Transaction interface with methods to begin and commit a system transaction.Furthermore, programmatic transaction management in a Hibernate application is exposed to the application developer via the Hibernate Transaction interface.You arent forced to use this APIHibernate also lets you begin and end JDBC transactions directly, but this usage is discouraged because it binds your code to direct JDBC.In a Java EE environment or if you installed it along with your Java SE application, a JTA compatible transaction manager is available, so you should call the JTA User.Transaction interface to begin and end a transaction programmatically.However, the Hibernate Transaction interface, as you may have guessed, also works on top of JTA.Well show you all these options and discuss portability concerns in more detail.Programmatic transaction demarcation with Java Persistence also has to work inside and outside of a Java EE application server.Outside of an application server, with plain Java SE, youre dealing with resource local transactions this is what the Entity.Transaction interface is good foryouve seen it in previous topics.Inside an application server, you call the JTA User.Transaction interface to begin and end a transaction.Lets summarize these interfaces and when theyre used java.ConnectionPlain JDBC transaction demarcation with set Auto.Commitfalse, commit, and rollback.It can but shouldnt be used in a Hibernate application, because it binds your application to a plain JDBC environment.TransactionUnified transaction demarcation in Hibernate applications.It works in a nonmanaged plain JDBC environment and also in an application server with JTA as the underlying system transaction service.The main benefit, however, is tight integration with persistence context managementfor example, a Session is flushed automatically when you commit.A persistence context can also have the scope of this transaction useful for conversations see the next topic.Use this API in Java SE if you cant have a JTA compatible transaction service.User.TransactionStandardized interface for programmatic transaction control in Java part of JTA.This should be your primary choice whenever you have a JTA compatible transaction service and want to control transactions programmatically.Entity.
|
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |