Java Persistence API Interview Questions & Answers

4 avg. rating (80% score) - 1 votes

Java Persistence API Interview Questions & Answers

Looking for Java Persistence API job? Don’t know how to prepare?. Then do not worry, we’ve a right answer for your job interview preparation. If you are preparing for Java Persistence API job interview and don’t know how to crack interview and what level or difficulty of questions to be asked in job interviews then go through Wisdomjobs Java Persistence API interview questions and answers page to crack your job interview. It is a collection of classes and methods to persistently store the vast amounts of data into a database. It provides Java developers with an object/relational mapping facility for managing relational data in Java applications. Please have a look at our Java Persistence API job interview questions and answers page to win your job.

Java Persistence API Interview Questions

Java Persistence API Interview Questions
    1. Question 1. What Is Jpa And Its Key Components?

      Answer :

      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.

    2. Question 2. What Is The Difference Between Persistence.xml And Hibernate.cfg.xml?

      Answer :

      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.

    3. Question 3. What Is An Entitymanager?

      Answer :

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

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

    4. Question 4. What Is An Entity?

      Answer :

      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.

    5. Question 5. Why To Use Jpa?

      Answer :

      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.

    6. Question 6. What Is Embeddable Classes?

      Answer :

      Entities may use persistent fields, persistent properties, or a combination of both. If the mapping annotations are applied to the entity’s instance variables, the entity uses persistent fields. If the mapping annotations are applied to the entity’s getter methods for JavaBeans-style properties, the entity uses persistent properties.

    7. Question 7. What Is Persistent Fields?

      Answer :

      If the entity class uses persistent fields, the Persistence runtime accesses entity-class instance variables directly. All fields not annotated javax.persistence.Transient or not marked as Java transient will be persisted to the data store. The object/relational mapping annotations must be applied to the instance variables.

    8. Question 8. What Is Persistent Properties?

      Answer :

      If the entity uses persistent properties, the entity must follow the method conventions of JavaBeans components. JavaBeans-style properties use getter and setter methods that are typically named after the entity class’s instance variable names. For every persistent property property of type Type of the entity, there is a getter method getProperty and setter method setProperty. If the property is a Boolean, you may use isProperty instead of getProperty. For example, if a Customer entity uses persistent properties and has a private instance variable called firstName, the class defines a getFirstName and setFirstName method for retrieving and setting the state of the firstName instance variable.

      The method signature for single-valued persistent properties are as follows:

      Type getProperty()
      void setProperty(Type type)

      The object/relational mapping annotations for persistent properties must be applied to the getter methods. Mapping annotations cannot be applied to fields or properties annotated @Transient or marked transient.

    9. Question 9. Explain Life Cycle Of A Jpa Entity.

      Answer :

      Key states that an entity might be in:

      1. New / Transient: An object is instantiated but not yet associated with an Entity Manager and has no representation in the database.
      2. Managed / Persisted.
      3. Detached: Detached entity objects are objects in a special state in which they are not managed by any EntityManager but still represent objects in the database. Detached objects are often returned from a persistence tier to the web layer where they can be displayed to the end-user in some form. Changes can be made to a detached dobject, but these changes won't be persisted to the database until the entity is reassociated with a persistence context (the entity is merged back to an EntityManager to become managed again).
      4. Removed.
      • The merge method's major task is to transfer the state from an unmanaged entity (passed as the argument) to its managed counterpart within the persistence context. 
      • merge deals with both new and detached entities. Merge causes either INSERT or UPDATE operation according to the sub-scenario (on the one hand it is more robust, on the other hand this robustness needn't be required.)
      • persist always causes INSERT SQL operation is executed (i.e. an exception may be thrown if the entity has already been inserted and thus the primary key violation happens.)

    10. Question 10. What Is Jpql?

      Answer :

      JPQL (Java Persistence Query Language) offers an object-oriented syntax for expressing query that is very similar to SQL. The language is interpreted at runtime, which means you cannot use the compiler to verify the correctness and integrity of a query. To adress this limitation, Hibernate includes a Criteria API, which allows queries to be expressed programmatically.

    11. Question 11. Example Of An Entity With Embedded Class.

      Answer :

      import java.io.Serializable;
      import java.util.Date;
      import javax.persistence.Basic;
      import javax.persistence.Column;
      import javax.persistence.EmbeddedId;
      import javax.persistence.Entity;
      import javax.persistence.JoinColumn;
      import javax.persistence.ManyToOne;
      import javax.persistence.NamedQueries;
      import javax.persistence.NamedQuery;
      import javax.persistence.Table;
      import javax.persistence.Temporal;
      import javax.persistence.TemporalType;
      @Entity
      @Table(name = "categoryparticipant")
      @NamedQueries({
      @NamedQuery(name = "Categoryparticipant.getCategoriesOfParticipant", query = "SELECT cp.category from Categoryparticipant cp where cp.participant.participantid= :participantid")
      })
      public class Categoryparticipant implements Serializable {
      private static final long serialVersionUID = 1L;
      @EmbeddedId
      protected CategoryparticipantPK categoryparticipantPK;
      @Basic(optional = false)
      @Column(name = "CreationDate")
      @Temporal(TemporalType.TIMESTAMP)
      private Date creationDate;
      @JoinColumn(name = "ParticipantId", referencedColumnName = "ParticipantId", insertable = false, updatable = false)
      @ManyToOne(optional = false)
      private Participant participant;
      @JoinColumn(name = "CategoryId", referencedColumnName = "CategoryId", insertable = false, updatable = false)
      @ManyToOne(optional = false)
      private Category category;
      public Categoryparticipant() {
      }
      public Categoryparticipant(CategoryparticipantPK categoryparticipantPK) {
      this.categoryparticipantPK = categoryparticipantPK;
      }
      public Categoryparticipant(CategoryparticipantPK categoryparticipantPK, Date creationDate) {
      this.categoryparticipantPK = categoryparticipantPK;
      this.creationDate = creationDate;
      }
      public Categoryparticipant(int categoryId, int participantId) {
      this.categoryparticipantPK = new CategoryparticipantPK(categoryId, participantId);
      }
      public CategoryparticipantPK getCategoryparticipantPK() {
      return categoryparticipantPK;
      }
      public void setCategoryparticipantPK(CategoryparticipantPK categoryparticipantPK) {
      this.categoryparticipantPK = categoryparticipantPK;
      }
      public Date getCreationDate() {
      return creationDate;
      }
      public void setCreationDate(Date creationDate) {
      this.creationDate = creationDate;
      }
      public Participant getParticipant() {
      return participant;
      }
      public void setParticipant(Participant participant) {
      this.participant = participant;
      }
      public Category getCategory() {
      return category;
      }
      public void setCategory(Category category) {
      this.category = category;
      }
      @Override
      public int hashCode() {
      int hash = 0;
      hash += (categoryparticipantPK != null ? categoryparticipantPK.hashCode() : 0);
      return hash;
      }
      @Override
      public boolean equals(Object object) {
      // TODO: Warning - this method won't work in the case the id fields are not set
      if (!(object instanceof Categoryparticipant)) {
      return false;
      }
      Categoryparticipant other = (Categoryparticipant) object;
      if ((this.categoryparticipantPK == null && other.categoryparticipantPK != null) || (this.categoryparticipantPK != null && !this.categoryparticipantPK.equals(other.categoryparticipantPK))) {
      return false;
      }
      return true;
      }
      @Override
      public String toString() {
      return "com.xchanging.entity.jpa.Categoryparticipant[categoryparticipantPK=" + categoryparticipantPK + "]";
      }
      }

    12. Question 12. Give An Example Of Embeddable Class For Previous Question Categoryparticipant Entity.

      Answer :

      import java.io.Serializable;
      import javax.persistence.Basic;
      import javax.persistence.Column;
      import javax.persistence.Embeddable;
      @Embeddable
      public class CategoryparticipantPK implements Serializable {
      @Basic(optional = false)
      @Column(name = "CategoryId")
      private int categoryId;
      @Basic(optional = false)
      @Column(name = "ParticipantId")
      private int participantId;
      public CategoryparticipantPK() {
      }
      public CategoryparticipantPK(int categoryId, int participantId) {
      this.categoryId = categoryId;
      this.participantId = participantId;
      }
      public int getCategoryId() {
      return categoryId;
      }
      public void setCategoryId(int categoryId) {
      this.categoryId = categoryId;
      }
      public int getParticipantId() {
      return participantId;
      }
      public void setParticipantId(int participantId) {
      this.participantId = participantId;
      }
      @Override
      public int hashCode() {
      int hash = 0;
      hash += (int) categoryId;
      hash += (int) participantId;
      return hash;
      }
      @Override
      public boolean equals(Object object) {
      // TODO: Warning - this method won't work in the case the id fields are not set
      if (!(object instanceof CategoryparticipantPK)) {
      return false;
      }
      CategoryparticipantPK other = (CategoryparticipantPK) object;

      if (this.categoryId != other.categoryId) {
      return false;
      }
      if (this.participantId != other.participantId) {
      return false;
      }
      return true;
      }
      @Override
      public String toString() {
      return "com.xchanging.entity.jpa.CategoryparticipantPK[categoryId=" + categoryId + ", participantId=" + participantId + "]";
      }
      }

    13. Question 13. Insert A Record Mechanism Using Jpa.

      Answer :

      @Override
      @Transactional
      public void create(Category entity) throws MeetingAppDAOException {
      try {
      logger.info("Enter - create()");
      super.create(entity);
      logger.info("Exit - create()");
      } catch (PersistenceException exception) {
      logger.error("create()::REASON OF EXCEPTION=" + exception.getMessage(), e);
      }
      }

    14. Question 14. How To Fetch A Record Using Namedquery?

      Answer :

      public Category findByCategoryId(Long categoryId) {
      try {
      logger.info("Enter - findByCategoryId()");
      Query lQuery = (Query) em.createNamedQuery("Category.findByCategoryId");
      Integer intValue = categoryId.intValue();
      lQuery.setParameter("categoryId", intValue);
      Category category = (Category) lQuery.getSingleResult();
      logger.info("Exit - findByCategoryId");
      return category;
      } catch (PersistenceException exception) {
      logger.debug(exception.getCause().getStackTrace());
      logger.error("CategoryDaoImpl::maxCategoryId()::REASON OF EXCEPTION=" + exception.getMessage() + exception.getCause());
      } finally {
      closeEntityManager();
      }
      }

    15. Question 15. Why Have You Introduced The New Java Persistence Api As Part Of The Java Ee 5 Platform?

      Answer :

      We introduced the Java Persistence API to the Java platform for two reasons. First, this new API simplifies the development of Java EE and Java SE applications using data persistence. Second, we wanted to get the entire Java community behind a single, standard persistence API.

    16. Question 16. What Are The Advantages Of The Java Persistence Api?

      Answer :

      The Java Persistence API draws upon the best ideas from persistence technologies such as Hibernate, TopLink, and JDO. Customers now no longer face the choice between incompatible non-standard persistence models for object/relational mapping. In addition, the Java Persistence API is usable both within Java SE environments as well as within Java EE, allowing many more developers to take advantage of a standard persistence API.

    17. Question 17. What Are Some Of The Main Features Of The Java Persistence Api?

      Answer :

      The Java Persistence API is a POJO persistence API for object/relational mapping. It contains a full object/relational mapping specification supporting the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java objects and a relational database. It supports a rich, SQL-like query language (which is a significant extension upon EJB QL) for both static and dynamic queries. It also supports the use of pluggable persistence providers.

    18. Question 18. Why Was The Java Persistence Api Developed As Part Of Jsr-220 (ejb 3.0)?

      Answer :

      The Java Persistence API originated as part of the work of the JSR 220 Expert Group to simplify EJB CMP entity beans. It soon became clear to the expert group, however, that a simplification of EJB CMP was not enough, and that what was needed was a POJO persistence framework in line with other O/R mapping technologies available in the industry. Once an Earlier Draft of the EJB 3.0 specification including the Java Persistence API was released, the JSR-220 Expert Group received many requests from the community that this work be made available beyond just the scope of EJB.

    19. Question 19. Why Didn't You Split Off The Java Persistence Api Work Into A Separate Jsr?

      Answer :

      We believed that leveraging the work in the context of JSR-220 would minimize risk and deliver a high quality result more quickly. Further, it was important that this API integrate smoothly and consistently with the rest of the simplifications to the EJB 3.0 APIs. It therefore seemed best to extend this ongoing project, and draw additional experts into the JSR-220 group as appropriate as the work expanded.

    20. Question 20. Why Didn't You Adopt Hibernate Or Jdo As The Persistence Api?

      Answer :

      We chose to combine the best ideas from many sources in the new persistence API and create a practical, easy to use API to meet the needs of a majority of Java EE and Java SE community members. The Java Persistence API is not based on any single existing persistence framework but incorporates--and improves upon--ideas contributed by many popular frameworks, including Hibernate, TopLink, JDO, and others.

    21. Question 21. What If I Want To Use The Java Persistence Api Outside Of The Java Ee Platform?

      Answer :

      The specification, RI, and TCK insure that the Java Persistence API works with Java SE as well as with Java EE. Passing the TCK for the Java SE portion allows vendors to be compliant with the Java Persistence API without having a Java EE certification.

    22. Question 22. What Will Happen To Other Data Persistence Apis Now That The Java Persistence Api Is Available?

      Answer :

      The Java Persistence API is now the standard API for persistence and object/relational mapping for the Java EE platform. Earlier APIs of course will not go away, but we expect that they will become less interesting once this new standard API is available.

    23. Question 23. How Will The Java Persistence Api Evolve Now That Jsr 220 Has Been Completed?

      Answer :

      We expect to spin off the Java Persistence API into its own new JSR for future evolution. This means subsequent versions of the Java Persistence API will not be tied to future EJB JSRs. We expect to continue to draw expertise from a diversity of sources, quite likely including many of the members of the JSR 220 Expert Group who helped define the Java Persistence API.

    24. Question 24. Will The Java Persistence Api Become Part Of Java Se?

      Answer :

      There are no current plans to include the Java Persistence API in Java SE. As the Java Persistence API evolves, however, it is likely that this issue will be considered by the Java SE expert group in a future Java SE release.

    25. Question 25. Are Changes Needed To Existing Ejb Cmp Applications?

      Answer :

      Existing EJB CMP applications continue to work unchanged, and EJB CMP technology will continue to be supported. There is no need to migrate existing applications to the Java Persistence API. Further, it is possible within the same application to combine continue usage of EJB CMP entity beans with new EJB components that make use of the Java Persistence API.

    26. Question 26. How Can I Obtain An Implementation Of The Java Persistence Api?

      Answer :

      We expect many vendors to offer products that include implementations of the Java Persistence API that can be used with Java SE or Java EE. You can obtain the open source GlassFish project implementation of the Java Persistence API.

Core Java Tutorial

Java Persistence Api Practice Tests

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd DMCA.com Protection Status

Core Java Tutorial