JPA Interview Questions for Freshers/JPA Interview Questions and Answers for Freshers & Experienced

What is the JPQL?

JPQL (Java Persistence Query Language) is an object-oriented query language used to perform database operations on persistent entities. JPQL uses the entity object model instead of the database table to execute SQL queries.

What is the unique inheritance strategy in Hibernate, but not in the JPA specification?

Unlike JPA, Hibernate has a unique inheritance strategy called implicit polymorphism.

What is the difference in Hibernate Entity requirements from the Entity requirements in the JPA specification?

1) A constructor with no arguments in Hibernate is not required to be public or protected, it is recommended that it be at least a package of visibility, but this is only a recommendation, if the Java security settings allow access to private fields, then it can be private.

2) JPA categorically requires not to use final classes, Hibernate only recommends not using such classes so that it can create a proxy for lazy loading, but it allows you to either turn off the Proxy proxy (lazy = false), or use an interface containing all mapping methods of this class (proxy annotation (proxyClass = interface.class))

What is meant by polymorphism (polymorphism) in JPQL queries (Java Persistence query language) and how to “turn it off”?

Unlike SQL, JPQL queries have automatic polymorphism, that is, each Entity request returns not only the objects of this Entity, but also objects of all its descendant classes, regardless of the inheritance strategy (for example, the select * from Animal query will return not only Animal objects, but also objects of Cat and Dog classes that are inherited from Animal). To eliminate this behavior, the TYPE function is used in the where condition (for example, select * from Animal a where TYPE (a) IN (Animal, Cat) will not return objects of the class Dog).

What is JPQL (Java Persistence query language) and how is it different from SQL?

JPQL (Java Persistence query language) is a query language, almost the same as SQL, but instead of the names and columns of database tables, it uses the names of the Entity classes and their attributes. The query parameters also use the data types of the attributes of the Entity, and not the database fields. Unlike SQL, JPQL has automatic polymorphism (see the next question). JPQL also uses functions that are not found in SQL: such as KEY (Map key), VALUE (Map value), TREAT (to cast a superclass to its heir object, downcasting), ENTRY, etc.

What is an Entitymanager?

The EntityManager is an API that manages the lifecycle of entity instances. They manages a set of entities that are defined by a persistence unit. Each EntityManager instance is associated with a persistence context.
The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities. The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit.

What is the difference between JPA and JDO?

JPA 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.
JDO, from an API point of view, is agnostic to the technology of the underlying datastore, whereas JPA is targeted to RDBMS datastores.
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, now it is developed as an Apache JDO project.

What is the Spring data repository?

Spring data repository is a very important feature of JPA. It helps in reducing a lot of boilerplate code. Moreover, it decreases the chance of errors significantly. This is also the key abstraction that is provided using the Repository interface. It takes the domain class to manage as well as the id type of the domain class as Type Arguments.
These Repositories are Java interfaces that allow you as the developer to define a data access contract. The Spring Data JPA framework can then inspect that contract, and automatically build the interface implementation under the covers for you.

What is the Spring data repository?

Spring data repository is a very important feature of JPA. It helps in reducing a lot of boilerplate code. Moreover, it decreases the chance of errors significantly. This is also the key abstraction that is provided using the Repository interface. It takes the domain class to manage as well as the id type of the domain class as Type Arguments.
These Repositories are Java interfaces that allow you as the developer to define a data access contract. The Spring Data JPA framework can then inspect that contract, and automatically build the interface implementation under the covers for you.

What is the role of Entity Manager in JPA?

An entity manager is responsible for the following roles in JPA.
The entity manager has the role to manage an object referenced by an entity.
It implements the API and encapsulates all of them within a single interface.
It is used for operations like read, delete and write an entity.

What are the two types of cache (cache) you know in JPA and what are they for?

JPA talks about two kinds of caches (cache):

1) first-level cache (first-level cache) —caches data from a single transaction;

2) second-level cache (second-level cache) —caches data for more than one transaction. The JPA provider can, but is not required to implement work with the second-level cache. This kind of cache can save access time and improve performance, but the downside is the ability to get outdated data.

What are the six types of locks (lock) described in the JPA specification (or what values ​​does the enum LockModeType in JPA have)?

JPA has six types of locks, list them in order of increasing reliability (from the most unreliable and fast, to the most reliable and slow):

1) NONE – without blocking

2) OPTIMISTIC (or READ synonym for JPA 1) – optimistic blocking

3) OPTIMISTIC_FORCE_INCREMENT (or WRITE synonym, remaining from JPA 1) – optimistic lock with forced increase of the version field,

4) PESSIMISTIC_READ – pessimistic lock for reading,

5) PESSIMISTIC_WRITE – pessimistic lock for write (and read),

6) PESSIMISTICI-PII-IZIETIHI, IHIETI , I, I, I, I, I, I, I, I; on record (and th with forced increase in the field of versioning.

What annotation can I manage JPA caching for this Entity?

Cacheable – allows you to enable or disable the use of a second-level cache (second-level cache) for this Entity (if the JPA provider supports caching and cache settings (second-level cache) are ENABLE_SELECTIVE or DISABLE_SELECTIVE, see question 41). Note that the property is inherited and if it is not blocked by the heirs, then caching will change for them too.

What is the Basic annotation for?

Basic – indicates the simplest type of data mapping on a database table column. Also in the annotation parameters you can specify fetch field access strategy and whether this field is required or not.

How does the detach operation affect the Entity objects of each of the four statuses?

1) If the status is Entity managed or removed, then as a result of the operation, the status of Entity (and all cascade-dependent objects) will become detached.

2) If the status is new or detached, then the operation is ignored.

How does the refresh operation affect the Entity objects of each of the four statuses?

1) If the status is Entity managed, then as a result of the operation all changes from the database of this Entity will be restored, also a refresh of all cascade-dependent objects will occur,

2) If the status is new, removed or detached, exception will be thrown out.

How does the operation merge affect the Entity objects of each of the four statuses?

1) If the detached state, then either the data will be copied to the existing managed entity with the same primary key, or a new managed is created into which the data is copied,

1) If the Entity is new, then a new managed entity will be created into which the past data will be copied object,

2) If the status is managed, the operation is ignored, but the operation merge will work on the cascade-dependent Entity, if their status is not managed,

3) If the status is removed, exception will be thrown immediately or at the commit stage of the transaction.

How does the remove operation affect the Entity objects of each of the four statuses?

1) If the status is Entity new, the operation is ignored, however dependent Entity can change the status to removed, if they have cascading change annotations and they had the status managed,

2) If the status is managed, then the status changes to removed and the object is recorded in the database removed during commit commit (remove operations will also occur for all cascade-dependent objects),

3) If status is removed, then the operation is ignored,

4) If detached, exception is thrown right away or at the commit stage of a transaction.

How does the operation persist on Entity objects of each of the four statuses?

1) If the status is Entity new, then it changes to managed and the object will be saved to the database when a transaction is committed or as a result of flush operations,

2) If the status is already managed, the operation is ignored, but dependent Entity can change the status to managed, if there are annotations of cascading changes,

3) If the status is removed, then it changes to managed,

4) If the status is detached, the exception will be thrown right away or at the commit stage of the transaction.

What are the four lifecycle status of an Entity Instance’s Life Cycle you can list?

An Entity object has four lifecycle status: new, managed, detached, or removed. Their description

1) new – the object has been created but has not yet generated primary keys and has not yet been saved in the database,

2) managed – the object has been created, managed by JPA, has generated primary keys,

3) detached – the object has been created, but not managed (or no longer managed) JPA,

4) removed – the object is created, managed by JPA, but will be deleted after commit’a transaction.

What is EntityManager and what are its main functions you can list?

EntityManager is an interface that describes an API for all basic operations on Enitity, data retrieval and other JPA entities. Essentially the main API for working with JPA. Basic operations:

1) For operations on Entity: persist (adding Entity under JPA control), merge (updating), remove (delete), refresh (updating data), detach (removing from management JPA), lock (blocking Enity from changes in other thread),

2) data Preparation: find (search and retrieval entity), createQuery, createNamedQuery, createNativeQuery , contains, createNamedStoredProcedureQuery, createStoredProcedureQuery

3) Preparation of other entities JPA: getTransaction, getEntityManagerFactory, getCriteriaBuilder, getMetamodel, getDelegate

4) Work with EntityGraph: createEntityGraph, getEntityGraph

4) General operations on EntityManager or all Entities: close, isOpen, getProperties, setProperty, clear.

What are the two types of fetch strategies in JPA do you know?

JPA describes two types of fetch strategies:

1) LAZY – these fields will be loaded only during the first access to this field,

2) EAGER – these fields will be loaded immediately.

What is the difference between @Column and @Basic annotations in JPA?

@Basic signifies that an attribute is to be persisted and a standard mapping is to be used. It has parameters which allow you to specify whether the attribute is to be lazily loaded and whether it's nullable. @Column allows you to specify the name of the column in the database to which the attribute is to be persisted.

What are the three types of Inheritance Mapping Strategies described in JPA?

JPA describes three inheritance mapping strategies (Inheritance Mapping Strategies), that is, how JPA will work with the classes derived from the Entity:

1) one table for the entire inheritance hierarchy ( a single table per class hierarchy ) – all enity one table, to identify the type of entity is determined by a special column “discriminator column” . For example, if there is an entity Animals with the descendant classes Cats and Dogs, with such a strategy, all entities are recorded in the Animals table, but they have an additional column, animalType, in which the value “cat” or “dog” is written respectively. Minusis that in the general table, all fields unique for each of the descendant classes will be created, which will be empty for all other descendant classes. For example, in the table of animals there will be the speed of climbing a tree from cats and whether the dog can bring sneakers from dogs, which will always be null for a dog and cat, respectively.

2) unifying strategy ( joined subclass strategy ) – in this strategy, each enity class stores data in its own table, but only unique columns (not inherited from ancestor classes) and the primary key, and all inherited columns are written to ancestor class tables a relationship is established between these tables, for example, in the case of the Animals classes (see above), there will be three tables of animals, cats, dogs, and only the key and speed of climbing will be recorded in cats, in dogs – the key and whether the dog can bring a stick , and in animals all the rest of the data of cats and dogs are c links th to the appropriate table. The downside is the performance loss from joining tables (join) for any operations.

3) one table for each class ( table per concrete class strategy ) – everything is simple here every individual class of successor has its own table, i.e. for cats and dogs (see above), all data will be recorded simply in the tables cats and dogs as if they did not have a common superclass at all. The downside is poor support for polymorphism (polymorphic relationships) and the fact that selecting all the classes in the hierarchy will require a large number of separate sql queries or using a UNION query.

What is Mapped Superclass?

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.

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 (see question 10),

* The Embeddable class must be marked with the Embeddable annotation or described in the XML configuration file JPA.

What is the Embeddable class?

An embeddable class is a class that is not used by itself, only as part of one or more Entity classes. An entity class can contain both single embedded classes and collections of such classes. Also such classes can be used as keys or map values. At run time, each embedded class belongs to only one object of the Entity class and cannot be used to transfer data between the objects of the Entity classes (that is, such a class is not a common data structure for different objects). In general, such a class serves to make the definition of common attributes for several Entity, we can assume that JPA simply embeds into the Entity instead of an object of this class, the attributes it contains.

How can we enable Spring Data JPA features?

To enable Spring data JPA features, first we have to define a configuration class and then, we can use @EnableJpaRepositoties annotation with it. This annotation will enable the features.

What is PlatformTransactionMangaer?

PlatformTransactionMangaer is an interface that extends TransactionManager. It is the central interface in Spring's transaction infrastructure.

What data types are allowed in the attributes of the Entity class (fields or properties)?

Valid attribute types for Entity classes are:

1. primitive types and their Java wrappers,
2. strings,
3. any Java serializable types (implementing the Serializable interface),
4. enums;
5. entity types;
6. embeddable classes
and collection types 1-6

What is the attribute of the Entity class in JPA terminology?

JPA indicates that it can work both with properties of classes (property), designed in the style of JavaBeans, or with fields (field), that is, class variables (instance variables). Both types of elements of the Entity class are called attributes of the Entity class.

What are the two types of elements in Entity classes. Or in other words, list two types of access (access) to the elements of the Entity classes.

JPA indicates that it can work both with properties of classes (property), designed in the style of JavaBeans, or with fields (field), that is, class variables (instance variables). Accordingly, the type of access will be either property access or field access.

What are the properties of an entity ?

* Persistability: An object is called persistent if it is stored in the database and can be accessed anytime.

* Persistent Identity: In Java, each entity is unique and represents an object identity. Similarly, when the object identity is stored in a database, then it is represented as persistence identity. This object identity is equivalent to the primary key in the database.

* Transactionality: A transaction is a set of operations that either fail or succeed as a unit. Transactions are a fundamental part of persistence.

* Granularity: Entities should not be primitives, primitive wrappers or built-in objects with single dimensional state.

Why does JPA have a @Transient annotation?

String test = "This is a test String and 'This is data we want'"
A: Java's transient keyword is used to denote that a field is not to be serialized, whereas JPA's @Transient annotation is used to indicate that a field is not to be persisted in the database, i.e. their semantics are different. Is it possible to set a default value for columns in JPA, and if, how is it done using annotations? Actually it is possible in JPA, although a little bit of a hack using the columnDefinition property of the @Column annotation, for example: @Column(name="Price", columnDefinition="Decimal(10,2) default '100.00'")

What are the different types of entity mapping ?

Following are the types of object-relational mapping: -
* One-to-one mapping: This mapping represents a single-valued association where an instance of one entity is associated with an instance of another entity. This means that one instance of source entity can be mapped with at most one instance of the target entity.
* One-To-Many mapping: This mapping comes into the category of collection-valued association where an entity is associated with a collection of other entities. This means that the instance of one entity can be mapped with any number of instances of another entity.
* Many-to-one mapping: This mapping represents a single-valued association where a collection of entities can be associated with the similar entity. This means that more than one row of an entity can refer to the same row of another entity.
* Many-to-many mapping: This mapping represents a collection-valued association where any number of entities can be associated with a collection of other entities. This means that more than one row of one entity can refer to more than one row of another entity.

In JPA EntityManager why use persist() over merge() ?

Persist: Persist takes an entity instance and adds it to the context making that instance managed.
Insert a new register to the database.
Merge:
Merge creates a new instance of your entity, copies the state from the supplied entity and then makes the new copy managed.
Find an attached object with the same id and update it.

Define entity and name the different properties of an entity.

An entity is a group of states bundled (or associated) together in a single unit. It behaves like an object. It also becomes a major constituent of the object-oriented paradigm.

Can you name the different types of entity mapping.

one-to-one mapping, one-to-many mapping, many-to-one mapping, and many-to-many mapping.

What JPA requirements for Entity classes can you list (at least six requirements)?

1) Entity class must be annotated with Entity or described in the XML configuration file JPA,

2) Entity class must contain a public or protected constructor with no arguments (it can also have constructors with arguments),

3) Entity class must be a top-level class (top -level class),

4) Entity class cannot be enum or interface,

5) Entity class cannot be final class,

6) Entity class cannot contain final fields or methods if they participate in mapping (persistent final methods or persistent final instance variables),

7) If an Entity class object is passed by value as a separate object (detached object), for example through a remote interface (through a remote interface), it must also implement a Serializable interface,

8) The Entity class fields should be directly accessible only to the methods of the Entity class and should not be directly accessible to other classes using this entity. Such classes should refer only to methods (getter / setter methods or other business logic methods in the Entity class),

9) The Enity class must contain a primary key, that is, an attribute or group of attributes that uniquely defines the record of this Enity class in the database.

Can Entity be an abstract class?

Perhaps, at the same time, it retains all the properties of the Entity, except that it cannot be directly initialized.

What is Entity?

Entity is a lightweight persistent domain object. The main program entity is the entity class, which can also use additional classes that can be used as auxiliary classes or to maintain state of the entity.

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, now it is developed as an Apache JDO project.

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, now it is developed as an Apache JDO project.

What is @Query used for?

Spring Data API provides many ways to define SQL query which can be executed and Query annotations one of them. The @Query is an annotation that is used to execute both JPQL and native SQL queries.

Is it possible to use JPA with noSQl databases?

In general, the JPA specification says only about mapping java objects into relational database tables, but there are a number of implementations of this standard for noSql databases: Kundera, DataNucleus, ObjectDB, and a number of others. Naturally, not all specification-specific features for relational databases are transferred to nosql databases completely.

What is the difference between JPA and Hibernate?

Hibernate is one of the most popular open source implementations of the latest specification (JPA 2.1). Even more likely the most popular, almost standard de facto. That is, JPA only describes rules and APIs, and Hibernate implements these descriptions, however Hibernate (like many other JPA implementations) has additional features not described in JPA (and not portable to other JPA implementations).

What is PagingAndSortingRepository?

The PagingAndSortingRepository provides methods that are used to retrieve entities using pagination and sorting. It extends the CrudRepository interface.

How can we create a custom repository in Spring data JPA?

To create a custom repository, we have to extend it to any of the following interfaces:
a) Repository
b) PagingAndSortingRepository
c) CrudRepository
d) JpaRepository
e) QueryByExampleRepository

Why is an interface not a class?

Interface is not a class because it does not contain concrete methods. It can contain only abstract methods.

What is the naming convention for finder methods in the Spring data repository interface?

This is another key feature of Spring Data JPA API which makes writing query method really easy. The finder method should use a special keyword, i.e. "find", followed by the name of the variable. For example, findByLastName().

What is the Spring data repository?

Spring data repository is a very important feature of JPA. It helps in reducing a lot of boilerplate code. Moreover, it decreases the chance of errors significantly. This is also the key abstraction that is provided using the Repository interface. It takes the domain class to manage as well as the id type of the domain class as Type Arguments.

What are some advantages of using JPA?

Here are some advantages of Java Persistence API or JPA:
JPA reduces the burden of interacting with databases.
Annotation in JPA reduces the cost of creating a definition file.
It is user-friendly.
JPA providers help merge applications.

What is JPA?

JPA stands for Java Persistence API. It is a Java specification used to persist data between the relational database and Java objects. It acts as a bridge between object-oriented domain models and relational databases. Since interaction with database from Java application is very common, JPA was created to standardize this interaction.

Search
R4R Team
R4R provides JPA Freshers questions and answers (JPA Interview Questions and Answers) .The questions on R4R.in website is done by expert team! Mock Tests and Practice Papers for prepare yourself.. Mock Tests, Practice Papers,JPA Interview Questions for Freshers,JPA Freshers & Experienced Interview Questions and Answers,JPA Objetive choice questions and answers,JPA Multiple choice questions and answers,JPA objective, JPA questions , JPA answers,JPA MCQs questions and answers Java, C ,C++, ASP, ASP.net C# ,Struts ,Questions & Answer, Struts2, Ajax, Hibernate, Swing ,JSP , Servlet, J2EE ,Core Java ,Stping, VC++, HTML, DHTML, JAVASCRIPT, VB ,CSS, interview ,questions, and answers, for,experienced, and fresher R4r provides Python,General knowledge(GK),Computer,PHP,SQL,Java,JSP,Android,CSS,Hibernate,Servlets,Spring etc Interview tips for Freshers and Experienced for JPA fresher interview questions ,JPA Experienced interview questions,JPA fresher interview questions and answers ,JPA Experienced interview questions and answers,tricky JPA queries for interview pdf,complex JPA for practice with answers,JPA for practice with answers You can search job and get offer latters by studing r4r.in .learn in easy ways .