JPA Interview Questions and Answers
Experienced / Expert level questions & answers
Ques 1. What is JPQL?
JPQL (Java Persistence Query Language) offers an object-oriented syntax for expressing queries that are 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 address this limitation, Hibernate includes a Criteria API, which allows queries to be expressed programmatically.
Ques 2. Example of an Entity with Embedded class.
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 + "]";
}
}
Ques 3. 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.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 + "]";
}
}
Ques 4. How to fetch a record using NamedQuery?
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();
}
}
Ques 5. What is the difference between JPA and JDO?
JPA (Java Persistence API) and Java Data Objects (JDO) are two specifications for storing java objects in databases.
If JPA is concentrated only on relational databases, then JDO is a more general specification that describes the ORM for any possible bases and repositories.
In principle, JPA can be viewed as part of the JDO specification specialized in relational databases, even though the API of these two specifications does not completely match.
The “developers” of specifications also differ – if JPA is developed as JSR, then JDO was first developed as JSR, and now it is developed as an Apache JDO project.
Ques 6. What requirements does JPA set for Embeddable classes?
- Such classes must satisfy the same rules as the Entity classes, except that they do not have to contain a primary key and be marked with the Entity annotation.
- The Embeddable class must be marked with the Embeddable annotation or described in the XML configuration file JPA.
Ques 7. What is a Mapped Superclass?
A mapped Superclass is a class from which Entity is inherited, it may contain JPA annotations, however, such a class is not Entity, it does not have to fulfill all the requirements set for Entity (for example, it may not contain a primary key).
Such a class cannot be used in EntityManager or Query operations. Such a class should be marked with the MappedSuperclass annotation or, respectively, described in the XML file.
Ques 8. On each of the four statuses of Entity objects, how are the operations persisted?
- For the new status, the object will get saved to the database after a transaction is committed and changes to the status managed.
- If the status is managed, it ignores the operation. But the status of the dependent Entity can be changed to 'managed' if the cascading annotations are there.
- For the removed status, it changes to managed thereafter.
- For the detached status, it throws the exception at the transaction's commit stage or right away.
Ques 9. What are the effects on the statuses of Entity objects of the merge operation?
- For the new status, a new managed entity is created, and the past data will be copied into it.
- For the managed status, it ignores the operation, but it works on the Entity dependent on cascading when the status is not managed.
- For the removed status, it throws the exception at the transaction's commit stage or right away.
- For the detached status, it either creates a new managed with the data copied or copies the data to the existing managed Entity
Ques 10. What are the effects on the statuses of Entity objects of the remove operation?
- For the new status, it ignores the operation, but the status changes to removed on the Entity dependent on cascading. Here the status shouldn't be managed.
- For the managed status, the status changes to removed thereafter, and the removed database records the object during the commit stage.
- For the removed status, it ignores the operation.
- For the detached status, it throws the exception at the transaction's commit stage or right away.
Ques 11. What are the effects on the statuses of Entity objects of the detach operation?
- For the new or detached status, it ignores the operation.
- For the managed or removed status, the Entity's status and also of the objects dependent on cascade become detached.
Ques 12. What are the effects on the statuses of Entity objects of the refresh operation?
- For the new, detached, or removed status, it throws out the exception.
- For the managed status, it restores all the changes from the database and refreshes all objects dependent on the cascade.
Ques 13. Mention the types of cache in JPA and their use.
There are two types of cache in JPA:
- First-level cache: Data is cached from a single transaction.
- Second-level transaction: Data is cached from more than one transaction.
Ques 14. What is the purpose of access annotation?
The access type for an entity class, embeddable, superclass, or individual attributes is defined by it. This defines the way JPA refers to entity attributes such as class properties or class fields having setters and getters.
Ques 15. What is the purpose of Basic annotation?
The simplest type of mapping of data on a column of the database is indicated by the basic annotation.
Also, the fetch field access strategy, as well as the requirement of the field, can be specified in the annotation parameters.
Ques 16. List the six types of locks available in JPA specification in ascending order.
The six types of locks are listed below in the ascending order of their reliability:
- NONE
- OPTIMISTIC
- OPTIMISTIC_FORCE_INCREMENT
- PESSIMISTIC_READ
- PESSIMISTIC_WRITE
- PESSIMISTICI
Ques 17. What options does JPA provide to set a second-level cache, or what values can be taken from the persistence.xml by the shared-cache-mode element?
The following five options are there:
- ALL
- NONE
- ENABLE_SELECTIVE
- DISABLE_SELECTIVE
- UNSPECIFIED
Ques 18. How can the JPA metadata that is the information about entity type, embeddable class, etc., be obtained?
The Metamodel interface is used by JPA for this purpose.
We can obtain this interface's object using the method of getMetamodel from an EntityManger or EntityMangerFactory.
Ques 19. What is a unique inheritance strategy not present in the JPA specification but present in Hibernate?
The implicit polymorphism strategy is present in Hibernate but it is not present in JPA.
Ques 20. What do you mean by JPQL (Java Persistence query language), and how does it differ from SQL?
- JPQL is almost similar to SQL, but the names of entity classes and attributes are used instead of the database columns.
- Also, the data types of entity attributes are used by the query parameters instead of database fields.
- There is automatic polymorphism in JPQL, unlike SQL. KEY, TREAT, VALUE, MAP, and ENTRY are some of the unique functions of JPQL.
Ques 21. What is polymorphism in JPQL queries?
This means that regardless of the inheritance strategy, the objects of all the descendant classes are returned in each entity request.
Ques 22. How can the polymorphism be turned off in JPQL?
We can use the TYPE function in the where condition for turning polymorphism off in JPQL.
Most helpful rated by users:
- What is ORM in JPA?
- What is an EntityManager?
- What is the difference between persistence.xml and hibernate.cfg.xml?
- What is an Entity?
- Why to use JPA?