YouTube Icon

Interview Questions.

Top 26 Java Persistence Api Interview Questions - Jul 26, 2022

fluid

Top 26 Java Persistence Api Interview Questions

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

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 component permits companies to be compliant with the Java Persistence API without having a Java EE certification.

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

We expect many carriers to provide merchandise that include implementations of the Java Persistence API that may be used with Java SE or Java EE. You can acquire the open source GlassFish assignment implementation of the Java Persistence API.

Q3. What Are The Advantages Of The Java Persistence Api?

The Java Persistence API draws upon the excellent ideas from persistence technology which includes Hibernate, TopLink, and JDO. Customers now no longer face the selection between incompatible non-popular staying power models for object/relational mapping. In addition, the Java Persistence API is usable each within Java SE environments as well as within Java EE, permitting many extra developers to take advantage of a fashionable endurance API.

Q4. What Is Persistent Fields?

If the entity elegance uses chronic fields, the Persistence runtime accesses entity-class example variables at once. All fields not annotated javax.Patience.Trient or not marked as Java trient may be continued to the information store. The object/relational mapping annotations must be applied to the instance variables.

Q5. What Is The Difference Between Persistence.Xml And Hibernate.Cfg.Xml?

When using JPA need patience.Xml and at the same time as using Hibernate API want hibernate.Cfg.Xml. When using JPA or Hibernate now not wanted both xmls, need the xml configuration document in step with JPA or Hibernate.

Q6. Why Was The Java Persistence Api Developed As Part Of Jsr-220 (ejb three.0)?

The Java Persistence API originated as a part of the paintings of the JSR 220 Expert Group to simplify EJB CMP entity be. It quickly have become clean to the expert organization, however, that a simplification of EJB CMP become not enough, and that what was needed became a POJO persistence framework in step with other O/R mapping technology available within the industry. Once an Earlier Draft of the EJB three.Zero specification including the Java Persistence API become launched, the JSR-220 Expert Group obtained many requests from the community that this work be made to be had beyond simply the scope of EJB.

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

The Java Persistence API is a POJO staying power API for item/relational mapping. It consists of a complete item/relational mapping specification supporting using Java language metadata annotations and/or XML descriptors to outline the mapping among Java objects and a relational database. It helps a rich, SQL-like query language (which is a massive extension upon EJB QL) for each static and dynamic queries. It additionally helps the usage of pluggable staying power companies.

Q8. How To Fetch A Record Using Namedquery?

Public Category findByCategoryId(Long categoryId) 

strive 

logger.Information("Enter - findByCategoryId()");

Query lQuery = (Query) em.CreateNamedQuery("Category.FindByCategoryId");

Integer intValue = categoryId.IntValue();

lQuery.SetParameter("categoryId", intValue);

Category class = (Category) lQuery.GetSingleResult();

logger.Info("Exit - findByCategoryId");

return category;

 trap (PersistenceException exception) 

logger.Debug(exception.GetCause().GetStackTrace());

logger.Mistakes("CategoryDaoImpl::maxCategoryId()::REASON OF EXCEPTION=" + exception.GetMessage() + exception.GetCause());

 ultimately 

closeEntityManager();

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

We selected to mix the first-class ideas from many resources inside the new patience API and create a sensible, clean to use API to satisfy the needs of a majority of Java EE and Java SE community individuals. The Java Persistence API isn't always based totally on any single existing endurance framework however includes--and improves upon--ideas contributed by way of many popular frameworks, including Hibernate, TopLink, JDO, and others.

Q10. Insert A Record Mechanism Using Jpa.

@Override

@Tractional

public void create(Category entity) throws MeetingAppDAOException 

try 

logger.Information("Enter - create()");

super.Create(entity);

logger.Information("Exit - create()");

 seize (PersistenceException exception) 

logger.Errors("create()::REASON OF EXCEPTION=" + exception.GetMessage(), e);

Q11. Will The Java Persistence Api Become Part Of Java Se?

There are not any modern pl to encompass the Java Persistence API in Java SE. As the Java Persistence API evolves, however, it's miles probably that this problem could be taken into consideration through the Java SE professional organization in a future Java SE launch.

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

The Java Persistence API is now the standard API for staying power and object/relational mapping for the Java EE platform. Earlier APIs of direction will not leave, but we count on that they may become less interesting as soon as this new trendy API is to be had.

Q13. What Is An Entitymanager?

Entity supervisor javax.Persistence.EntityManager offers the operations from and to the database, e.G. Discover objects, persists them, get rid of gadgets from the database, and so on. Entities which can be managed by means of an EntityManager will routinely propagate those changes to the database (if this takes place within a dedicate statement). These objects are called persistent object. If the Entity Manager is closed (through near()) then the managed entities are in a indifferent state. These are called the detached items. If you want synchronize them once more with the database, the a Entity Manager gives the merge() technique. Once merged, the item(s) becomes perstent objects again.

The EntityManager is the API of the patience context, and an EntityManager can be injected at once in to a DAO without requiring a JPA Template. The Spring Container is capable of appearing as a JPA box and of injecting the EntityManager by means of honoring the @PersistenceContext (each as subject-stage and a technique-level annotation).

Entity manager javax.Patience.EntityManager presents the operations from and to the database, e.G. Discover items, persists them, put off gadgets from the database, and so on. Entities that are controlled by means of an EntityManager will robotically propagate these modifications to the database (if this occurs within a commit declaration). These gadgets are known as persistent item. If the Entity Manager is closed (thru close()) then the managed entities are in a detached state. These are called the detached objects. If you need synchronize them once more with the database, the a Entity Manager provides the merge() technique. Once merged, the item(s) will become perstent gadgets again.

The EntityManager is the API of the patience context, and an EntityManager can be injected without delay in to a DAO with out requiring a JPA Template. The Spring Container is able to appearing as a JPA container and of injecting the EntityManager by means of honoring the @PersistenceContext (both as field-level and a method-degree annotation).

Q14. Are Changes Needed To Existing Ejb Cmp Applications?

Existing EJB CMP packages hold to paintings unchanged, and EJB CMP generation will remain supported. There is no want to migrate present packages to the Java Persistence API. Further, it's miles feasible inside the equal software to mix continue usage of EJB CMP entity be with new EJB components that make use of the Java Persistence API.

Q15. Example Of An Entity With Embedded Class.

Import java.Io.Serializable;

import java.Util.Date;

import javax.Persistence.Basic;

import javax.Patience.Column;

import javax.Staying power.EmbeddedId;

import javax.Staying power.Entity;

import javax.Persistence.JoinColumn;

import javax.Endurance.ManyToOne;

import javax.Staying power.NamedQueries;

import javax.Patience.NamedQuery;

import javax.Endurance.Table;

import javax.Persistence.Temporal;

import javax.Staying power.TemporalType;

@Entity

@Table(name = "categoryparticipant")

@NamedQueries(

@NamedQuery(call = "Categoryparticipant.GetCategoriesOfParticipant", question = "SELECT cp.Category from Categoryparticipant cp where cp.Player.Participantid= :participantid")

)

public elegance Categoryparticipant implements Serializable 

private static final lengthy serialVersionUID = 1L;

@EmbeddedId

covered CategoryparticipantPK categoryparticipantPK;

@Basic(non-compulsory = false)

@Column(name = "CreationDate")

@Temporal(TemporalType.TIMESTAMP)

non-public Date creationDate;

@JoinColumn(name = "ParticipantId", referencedColumnName = "ParticipantId", insertable = fake, updatable = false)

@ManyToOne(optional = fake)

private Participant player;

@JoinColumn(name = "CategoryId", referencedColumnName = "CategoryId", insertable = fake, updatable = fake)

@ManyToOne(non-compulsory = fake)

non-public 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() 

go back creationDate;

public void setCreationDate(Date creationDate) 

this.CreationDate = creationDate;

public Participant getParticipant() 

go back player;

public void setParticipant(Participant participant) 

this.Player = player;

public Category getCategory() 

return class;

public void setCategory(Category category) 

this.Class = category;

@Override

public int hashCode() 

int hash = zero;

hash += (categoryparticipantPK != null ? CategoryparticipantPK.HashCode() : zero);

go back hash;

@Override

public boolean equals(Object object) 

// TODO: Warning - this approach might not work in the case the identity fields aren't set

if (!(item instanceof Categoryparticipant)) 

go back fake;

Categoryparticipant other = (Categoryparticipant) object;

if ((this.CategoryparticipantPK == null && different.CategoryparticipantPK != null) different.CategoryparticipantPK))) 

return fake;

go back real;

@Override

public String toString() 

go back "com.Xchanging.Entity.Jpa.Categoryparticipant[categoryparticipantPK=" + categoryparticipantPK + "]";

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

We believed that leveraging the work in the context of JSR-220 could limit chance and supply a excessive exceptional result greater quickly. Further, it turned into critical that this API combine easily and continually with the rest of the simplifications to the EJB 3.Zero APIs. It consequently regarded satisfactory to increase this ongoing mission, and draw additional specialists into the JSR-220 group as appropriate as the work multiplied.

Q17. What Is Persistent Properties?

If the entity uses continual residences, the entity have to follow the approach conventions of JavaBe additives. JavaBe-style properties use getter and setter strategies which are generally named after the entity magnificence’s example variable names. For every continual property property of kind Type of the entity, there may be a getter method getProperty and setter technique setProperty. If the belongings is a Boolean, you can use isProperty in place of getProperty. For example, if a Customer entity makes use of chronic houses and has a non-public example variable known as firstName, the magnificence defines a getFirstName and setFirstName approach for retrieving and placing the state of the firstName example variable.

The method signature for unmarried-valued continual residences are as follows:

Type getProperty()

void setProperty(Type type)

The object/relational mapping annotations for persistent houses ought to be applied to the getter strategies. Mapping annotations cannot be implemented to fields or residences annotated @Trient or marked trient.

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

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 programs the use of information patience. Second, we wanted to get the complete Java community behind a unmarried, widespread endurance API.

Q19. What Is Jpql?

JPQL (Java Persistence Query Language) gives an item-orientated syntax for expressing question this is very just like SQL. The language is interpreted at runtime, which me you cannot use the compiler to confirm the correctness and integrity of a query. To adress this limitation, Hibernate consists of a Criteria API, which permits queries to be expressed programmatically.

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

Import java.Io.Serializable;

import javax.Persistence.Basic;

import javax.Persistence.Column;

import javax.Endurance.Embeddable;

@Embeddable

public elegance CategoryparticipantPK implements Serializable 

@Basic(non-obligatory = fake)

@Column(call = "CategoryId")

personal int categoryId;

@Basic(elective = false)

@Column(name = "ParticipantId")

non-public int participantId;

public CategoryparticipantPK() 

public CategoryparticipantPK(int categoryId, int participantId) 

this.CategoryId = categoryId;

this.ParticipantId = participantId;

public int getCategoryId() 

go back 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;

go back hash;

@Override

public boolean equals(Object object) 

// TODO: Warning - this approach won't paintings in the case the id fields aren't set

if (!(object instanceof CategoryparticipantPK)) 

go back false;

CategoryparticipantPK other = (CategoryparticipantPK) item;

if (this.CategoryId != other.CategoryId) 

go back fake;

if (this.ParticipantId != different.ParticipantId) 

return fake;

go back actual;

@Override

public String toString() 

return "com.Xchanging.Entity.Jpa.CategoryparticipantPK[categoryId=" + categoryId + ", participantId=" + participantId + "]";

Q21. Why To Use Jpa?

Using JPA does no longer tie you to Hibernate. JPA offers you maximum of the functions of undeniable old Hibernate, except:

No standards queries in JPA 2.@Criteria question is a neat characteristic of Hibernate that constructs question using Java-based totally combinators in preference to alternate query language, getting the benefit of IntelliSense and Eclipse’s refactoring gear.

JPA doesn’t have Hibernate’s DeleteOrphan cascade type. 

Delete Orphan is a useful annotation that directs Hibernate to deletes entities in a group if the discern is deleted, stopping orphaning.

JPA doesn’t have an equivalent to Hibernate’s ScrollableResults.

Q22. Explain Life Cycle Of A Jpa Entity.

Key states that an entity is probably in:

New / Trient: An object is instantiated but no longer but related to an Entity Manager and has no representation within the database.

Managed / Persisted.

Detached: Detached entity objects are gadgets in a special nation in which they're now not managed with the aid of any EntityManager however still represent items inside the database. Detached gadgets are regularly again from a persistence tier to the net layer wherein they may be exhibited to the end-consumer in a few form. Changes may be made to a detached dobject, however these modifications won't be persevered to the database until the entity is reassociated with a endurance context (the entity is merged back to an EntityManager to grow to be controlled again).

Removed.

The merge technique's most important challenge is to trfer the state from an unmanaged entity (surpassed as the argument) to its controlled counterpart inside the patience context. 

Merge deals with both new and indifferent entities. Merge causes either INSERT or UPDATE operation in line with the sub-state of affairs (on the only hand it is greater sturdy, alternatively this robustness need not be required.)

persist usually reasons INSERT SQL operation is accomplished (i.E. An exception may be thrown if the entity has already been inserted and therefore the primary key violation takes place.)

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

We assume to spin off the Java Persistence API into its own new JSR for future evolution. This me next variations of the Java Persistence API will now not be tied to future EJB JSRs. We expect to continue to attract expertise from a diversity of sources, quite probable which includes among the individuals of the JSR 220 Expert Group who helped define the Java Persistence API.

Q24. What Is Jpa And Its Key Components?

Mapping between database tables and java gadgets called ORM (Object Relational Mapping). JPA (Java Persistence API) offers and ORM facility for handling relational tables in Java applications. It is a specification and few implementations are like Hibernate, JDO, EJB, Toplink. By the use of JPA can be fetched statistics, insert, replace and many others.

Q25. What Is An Entity?

A magnificence which ought to be continued in a database it should be annotated with javax.Staying power.Entity. Such a class is known as Entity. An times of the elegance could be a row inside the man or woman desk. So, the columns within the individual table can be mapped to the Person java item annotated as @Entity.

While insert, update or fetch document to or from the database we use entity as mapping with relational tables.

Q26. What Is Embeddable Classes?

Entities might also use chronic fields, continual properties, or a aggregate of each. If the mapping annotations are implemented to the entity’s example variables, the entity makes use of persistent fields. If the mapping annotations are carried out to the entity’s getter techniques for JavaBe-fashion residences, the entity makes use of continual residences.




CFG