JPA Interview Questions and Answers
Ques 1. What is JPA and its key components?
Ans. Mapping between database tables and java objects called ORM (Object Relational Mapping). JPA (Java Persistence API) provides and ORM facility for managing relational tables in Java applications. It is a specification and few implementations are like Hibernate, JDO, EJB, Toplink. By using JPA can be fetched data, insert, update etc.
Ques 2. What is the difference between persistence.xml and hibernate.cfg.xml?Ans. When using JPA need persistence.xml and while using Hibernate API need hibernate.cfg.xml. When using JPA or Hibernate not needed both xmls, need the xml configuration file according to JPA or Hibernate.
Ques 3. What is an EntityManager?Ans. Entity manager javax.persistence.EntityManager provides the operations from and to the database, e.g. find objects, persists them, remove objects from the database, etc. Entities which are managed by an EntityManager will automatically propagate these changes to the database (if this happens within a commit statement). These objects are known as persistent object. If the Entity Manager is closed (via close()) then the managed entities are in a detached state. These are known as the detached objects. If you want synchronize them again with the database, the a Entity Manager provides the merge() method. Once merged, the object(s) becomes perstent objects again.
The EntityManager is the API of the persistence context, and an EntityManager can be injected directly in to a DAO without requiring a JPA Template. The Spring Container is capable of acting as a JPA container and of injecting the EntityManager by honoring the @PersistenceContext (both as field-level and a method-level annotation).
Ques 4. What is an Entity?Ans. A class which should be persisted in a database it must be annotated with javax.persistence.Entity. Such a class is called Entity. An instances of the class will be a row in the person table. So, the columns in the person table will be mapped to the Person java object annotated as @Entity.
While insert, update or fetch record to or from the database we use entity as mapping with relational tables.
Ques 5. Why to use JPA?Ans. JPA is the standard, and standards are good!
Using JPA does not tie you to Hibernate.
JPA gives you most of the features of plain old Hibernate, except:
No criteria queries in JPA 2.0. Criteria query is a neat feature of Hibernate that constructs query using Java-based combinators instead of alternate query language, getting the benefit of IntelliSense and Eclipse’s refactoring tools.
JPA doesn’t have Hibernate’s DeleteOrphan cascade type.
Delete Orphan is a useful annotation that directs Hibernate to deletes entities in a collection if the parent is deleted, preventing orphaning.
JPA doesn’t have an equivalent to Hibernate’s ScrollableResults.
Most helpful rated by users: