YouTube Icon

Interview Questions.

Top 100+ Java Persistence Api Interview Questions And Answers - May 31, 2020

fluid

Top 100+ Java Persistence Api Interview Questions And Answers

Question 1. What Is Jpa And Its Key Components?

Answer :

Mapping between database tables and java gadgets referred to as ORM (Object Relational Mapping). JPA (Java Persistence API) presents and ORM facility for handling relational tables in Java programs. It is a specification and few implementations are like Hibernate, JDO, EJB, Toplink. By the usage of JPA can be fetched records, insert, update etc.

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

Answer :

When the usage of JPA want patience.Xml and while using Hibernate API need hibernate.Cfg.Xml. When using JPA or Hibernate not needed each xmls, want the xml configuration record in keeping with JPA or Hibernate.

Core Java Interview Questions
Question three. What Is An Entitymanager?

Answer :

Entity manager javax.Persistence.EntityManager gives the operations from and to the database, e.G. Locate objects, persists them, take away gadgets from the database, and so on. Entities that are managed by way of an EntityManager will mechanically propagate these adjustments to the database (if this occurs inside a commit announcement). These gadgets are referred to as continual object. If the Entity Manager is closed (through close()) then the controlled entities are in a detached country. These are referred to as the detached gadgets. If you want synchronize them again with the database, the a Entity Manager affords the merge() method. Once merged, the item(s) will become perstent gadgets again.

The EntityManager is the API of the endurance context, and an EntityManager can be injected at once in to a DAO with out requiring a JPA Template. The Spring Container is capable of appearing as a JPA field and of injecting the EntityManager via honoring the @PersistenceContext (each as subject-degree and a way-level annotation).

Entity supervisor javax.Patience.EntityManager provides the operations from and to the database, e.G. Find objects, persists them, remove items from the database, and many others. Entities that are managed by using an EntityManager will mechanically propagate those changes to the database (if this happens inside a dedicate declaration). These items are called continual object. If the Entity Manager is closed (through close()) then the controlled entities are in a detached nation. These are known as the indifferent objects. If you need synchronize them once more with the database, the a Entity Manager affords the merge() technique. Once merged, the item(s) becomes perstent items again.

The EntityManager is the API of the patience context, and an EntityManager can be injected immediately in to a DAO without requiring a JPA Template. The Spring Container is capable of performing as a JPA field and of injecting the EntityManager by using honoring the @PersistenceContext (both as area-level and a way-degree annotation).

Question four. What Is An Entity?

Answer :

A elegance which must be endured in a database it must be annotated with javax.Patience.Entity. Such a class is known as Entity. An instances of the class can be a row within the character desk. So, the columns within the person table will be mapped to the Person java object annotated as @Entity.

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

Core Java Tutorial
Question five. Why To Use Jpa?

Answer :

Using JPA does no longer tie you to Hibernate. JPA gives you most of the features of plain old Hibernate, except:

No criteria queries in JPA 2.Zero. Criteria question is a neat function of Hibernate that constructs query using Java-based totally combinators rather than change question language, getting the advantage of IntelliSense and Eclipse’s refactoring tools.

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

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

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

Java-Springs Interview Questions
Question 6. What Is Embeddable Classes?

Answer :

Entities may additionally use persistent fields, continual houses, or a combination of each. If the mapping annotations are implemented to the entity’s example variables, the entity makes use of continual fields. If the mapping annotations are applied to the entity’s getter strategies for JavaBeans-fashion homes, the entity uses persistent homes.

Question 7. What Is Persistent Fields?

Answer :

If the entity elegance uses persistent fields, the Persistence runtime accesses entity-magnificence example variables without delay. All fields no longer annotated javax.Endurance.Transient or now not marked as Java brief might be endured to the statistics shop. The item/relational mapping annotations need to be applied to the instance variables.

Java-Springs Tutorial Hibernate Interview Questions
Question 8. What Is Persistent Properties?

Answer :

If the entity uses continual residences, the entity need to follow the approach conventions of JavaBeans components. JavaBeans-fashion properties use getter and setter techniques that are normally named after the entity elegance’s instance variable names. For every persistent belongings belongings of kind Type of the entity, there's a getter approach getProperty and setter method setProperty. If the belongings is a Boolean, you may use isProperty instead of getProperty. For example, if a Customer entity makes use of chronic homes and has a personal instance variable called firstName, the class defines a getFirstName and setFirstName approach for retrieving and placing the state of the firstName example variable.

The approach signature for unmarried-valued persistent properties are as follows:

Type getProperty()
void setProperty(Type type)

The item/relational mapping annotations for chronic houses have to be carried out to the getter strategies. Mapping annotations can not be implemented to fields or houses annotated @Transient or marked transient.

Question nine. Explain Life Cycle Of A Jpa Entity.

Answer :

Key states that an entity might be in:

New / Transient: An object is instantiated however not but related to an Entity Manager and has no representation within the database.
Managed / Persisted.
Detached: Detached entity gadgets are gadgets in a unique kingdom in which they're not controlled by way of any EntityManager but nevertheless represent gadgets inside the database. Detached items are frequently back from a patience tier to the net layer in which they can be exhibited to the end-user in some form. Changes may be made to a detached dobject, but these changes might not be persevered to the database until the entity is reassociated with a patience context (the entity is merged returned to an EntityManager to turn out to be controlled again).
Removed.
The merge method's predominant mission is to switch the nation from an unmanaged entity (handed because the argument) to its managed counterpart in the endurance context. 
Merge offers with each new and indifferent entities. Merge reasons either INSERT or UPDATE operation according to the sub-scenario (on the one hand it is more sturdy, alternatively this robustness need not be required.)
persist always reasons INSERT SQL operation is carried out (i.E. An exception may be thrown if the entity has already been inserted and hence the primary key violation occurs.)
JBOSS Interview Questions
Question 10. What Is Jpql?

Answer :

JPQL (Java Persistence Query Language) gives an item-oriented syntax for expressing query that is very just like SQL. The language is interpreted at runtime, this means that you can't use the compiler to verify the correctness and integrity of a question. To adress this issue, Hibernate includes a Criteria API, which permits queries to be expressed programmatically.

Hibernate Tutorial
Question eleven. Example Of An Entity With Embedded Class.

Answer :

import java.Io.Serializable;
import java.Util.Date;
import javax.Persistence.Basic;
import javax.Endurance.Column;
import javax.Patience.EmbeddedId;
import javax.Endurance.Entity;
import javax.Patience.JoinColumn;
import javax.Endurance.ManyToOne;
import javax.Patience.NamedQueries;
import javax.Persistence.NamedQuery;
import javax.Endurance.Table;
import javax.Patience.Temporal;
import javax.Staying power.TemporalType;
@Entity
@Table(name = "categoryparticipant")
@NamedQueries(
@NamedQuery(name = "Categoryparticipant.GetCategoriesOfParticipant", question = "SELECT cp.Class from Categoryparticipant cp wherein cp.Participant.Participantid= :participantid")
)
public magnificence Categoryparticipant implements Serializable 
personal static very last lengthy serialVersionUID = 1L;
@EmbeddedId
blanketed CategoryparticipantPK categoryparticipantPK;
@Basic(optional = false)
@Column(call = "CreationDate")
@Temporal(TemporalType.TIMESTAMP)
non-public Date creationDate;
@JoinColumn(name = "ParticipantId", referencedColumnName = "ParticipantId", insertable = false, updatable = fake)
@ManyToOne(optional = false)
private Participant participant;
@JoinColumn(call = "CategoryId", referencedColumnName = "CategoryId", insertable = fake, updatable = fake)
@ManyToOne(optionally available = false)
personal 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() 
go back 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 player) 
this.Player = participant;

public Category getCategory() 
go back category;

public void setCategory(Category class) 
this.Category = category;

@Override
public int hashCode() 
int hash = zero;
hash += (categoryparticipantPK != null ? CategoryparticipantPK.HashCode() : 0);
go back hash;

@Override
public boolean equals(Object item) 
// TODO: Warning - this approach might not work inside the case the identification fields are not set
if (!(object instanceof Categoryparticipant)) 
go back false;

Categoryparticipant other = (Categoryparticipant) item;
if ((this.CategoryparticipantPK == null && different.CategoryparticipantPK != null) other.CategoryparticipantPK))) 
return false;

return real;

@Override
public String toString() 
go back "com.Xchanging.Entity.Jpa.Categoryparticipant[categoryparticipantPK=" + categoryparticipantPK + "]";

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

Answer :

import java.Io.Serializable;
import javax.Persistence.Basic;
import javax.Patience.Column;
import javax.Endurance.Embeddable;
@Embeddable
public elegance CategoryparticipantPK implements Serializable 
@Basic(non-compulsory = fake)
@Column(name = "CategoryId")
non-public int categoryId;
@Basic(non-obligatory = fake)
@Column(call = "ParticipantId")
private 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;
return hash;

@Override
public boolean equals(Object item) 
// TODO: Warning - this approach may not paintings in the case the id fields aren't set
if (!(object instanceof CategoryparticipantPK)) 
go back false;

CategoryparticipantPK other = (CategoryparticipantPK) object;

if (this.CategoryId != other.CategoryId) 
go back fake;

if (this.ParticipantId != other.ParticipantId) 
go back false;

return true;

@Override
public String toString() 
return "com.Xchanging.Entity.Jpa.CategoryparticipantPK[categoryId=" + categoryId + ", participantId=" + participantId + "]";

Core Java Interview Questions
Question 13. Insert A Record Mechanism Using Jpa.

Answer :

@Override
@Transactional
public void create(Category entity) throws MeetingAppDAOException 
attempt 
logger.Info("Enter - create()");
exquisite.Create(entity);
logger.Data("Exit - create()");
 seize (PersistenceException exception) 
logger.Error("create()::REASON OF EXCEPTION=" + exception.GetMessage(), e);

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

Answer :

public Category findByCategoryId(Long categoryId) 
try 
logger.Data("Enter - findByCategoryId()");
Query lQuery = (Query) em.CreateNamedQuery("Category.FindByCategoryId");
Integer intValue = categoryId.IntValue();
lQuery.SetParameter("categoryId", intValue);
Category category = (Category) lQuery.GetSingleResult();
logger.Information("Exit - findByCategoryId");
go back class;
 trap (PersistenceException exception) 
logger.Debug(exception.GetCause().GetStackTrace());
logger.Errors("CategoryDaoImpl::maxCategoryId()::REASON OF EXCEPTION=" + exception.GetMessage() + exception.GetCause());
 ultimately 
closeEntityManager();

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

Answer :

We brought the Java Persistence API to the Java platform for two reasons. First, this new API simplifies the improvement of Java EE and Java SE applications the use of statistics persistence. Second, we wanted to get the complete Java network at the back of a unmarried, preferred persistence API.

Java Management Extensions (JMX) Interview Questions
Question sixteen. What Are The Advantages Of The Java Persistence Api?

Answer :

The Java Persistence API attracts upon the satisfactory thoughts from staying power technologies including Hibernate, TopLink, and JDO. Customers now not face the choice among incompatible non-fashionable persistence fashions for item/relational mapping. In addition, the Java Persistence API is usable each inside Java SE environments in addition to within Java EE, permitting many greater builders to take benefit of a trendy patience API.

Log4j Tutorial
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 item/relational mapping. It carries a complete object/relational mapping specification supporting the use of Java language metadata annotations and/or XML descriptors to define the mapping between Java gadgets and a relational database. It helps a rich, SQL-like query language (that's a significant extension upon EJB QL) for both static and dynamic queries. It also supports the usage of pluggable endurance vendors.

RichFaces Interview Questions
Question 18. Why Was The Java Persistence Api Developed As Part Of Jsr-220 (ejb three.0)?

Answer :

The Java Persistence API originated as a part of the paintings of the JSR 220 Expert Group to simplify EJB CMP entity beans. It quickly have become clear to the professional organization, but, that a simplification of EJB CMP changed into now not enough, and that what turned into needed changed into a POJO persistence framework consistent with other O/R mapping technologies available inside the industry. Once an Earlier Draft of the EJB 3.0 specification along with the Java Persistence API become released, the JSR-220 Expert Group received many requests from the community that this work be made to be had past simply the scope of EJB.

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

Answer :

We believed that leveraging the paintings within the context of JSR-220 might decrease danger and supply a high first-rate end result greater speedy. Further, it changed into vital that this API combine smoothly and continually with the relaxation of the simplifications to the EJB three.Zero APIs. It consequently seemed exceptional to extend this ongoing assignment, and draw extra experts into the JSR-220 institution as appropriate because the paintings extended.

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

Answer :

We chose to mix the exceptional thoughts from many assets within the new endurance API and create a realistic, smooth to apply API to meet the needs of a majority of Java EE and Java SE community individuals. The Java Persistence API isn't always primarily based on any unmarried existing patience framework but consists of--and improves upon--ideas contributed by using many famous frameworks, together with Hibernate, TopLink, JDO, and others.

Spring MVC Framework Interview Questions
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 in addition to with Java EE. Passing the TCK for the Java SE element allows vendors to be compliant with the Java Persistence API while not having a Java EE certification.

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 usual API for staying power and item/relational mapping for the Java EE platform. Earlier APIs of path will not depart, however we count on that they'll end up less thrilling once this new trendy API is to be had.

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 approach next variations of the Java Persistence API will no longer be tied to future EJB JSRs. We assume to hold to attract knowledge from a variety of assets, quite probably together with many of the contributors of the JSR 220 Expert Group who helped outline the Java Persistence API.

Spring Security Interview Questions
Question 24. Will The Java Persistence Api Become Part Of Java Se?

Answer :

There aren't any modern-day plans to include the Java Persistence API in Java SE. As the Java Persistence API evolves, but, it is probably that this problem could be taken into consideration via the Java SE expert institution in a future Java SE release.

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

Answer :

Existing EJB CMP programs preserve to paintings unchanged, and EJB CMP era will remain supported. There is no want to migrate present packages to the Java Persistence API. Further, it is viable within the identical software to mix maintain utilization of EJB CMP entity beans with new EJB components that employ the Java Persistence API.

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

Answer :

We anticipate many carriers to offer products that encompass implementations of the Java Persistence API that may be used with Java SE or Java EE. You can obtain the open source GlassFish challenge implementation of the Java Persistence API.

JAXB Interview Questions




CFG