JPA/Hibernate Flashcards

1
Q

What is the difference between JPA and Hibernate?

A

JPA is not an implementation. It is only a Java specification.
Hibernate is an implementation of JPA. Hence, the common standard which is given by JPA is followed by Hibernate.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the advantages of Hibernate over JDBC?

A

[1] Hibernate removes a lot of boiler-plate code that comes with JDBC API, the code looks more cleaner and readable.

[3] Hibernate Query Language (HQL) is more object oriented and close to java programming language. For JDBC, we need to write native sql queries.

[3] Hibernate configuration helps us in using JDBC like connection as well as JNDI DataSource for connection pool. This is very important feature in enterprise application and completely missing in JDBC API.

[4] Avoid SQL injections

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is Hibernate SessionFactory?

A

SessionFactory is the factory class used to get the Session objects. SessionFactory is responsible to read the hibernate configuration parameters and connect to the database and provide Session objects.

Usually an application has a single SessionFactory instance and threads servicing client requests obtain Session instances from this factory. The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping. SessionFactory also provide methods to get the Class metadata and Statistics instance to get the stats of query executions, second level cache details etc.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is Hibernate SessionFactory thread safe?

A

Hibernate SessionFactory is thread safe?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is Hibernate Session object?

A

Hibernate Session is the interface between java application layer and hibernate. This is the core interface used to perform database operations.

Lifecycle of a session is bound by the beginning and end of a transaction.

Session provide methods to perform create, read, update and delete operations for a persistent object.
We can execute HQL queries, SQL native queries and create criteria using Session object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Is Hibernate Session object thread safe?

A

Hibernate Session object is not thread safe, every thread should get it’s own session instance and close it after it’s work is finished.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

[1] What is hibernate caching? Explain Hibernate’s first level cache.
[2] When the first level cache is used to traverse the relationship

https://vladmihalcea.com/jpa-hibernate-first-level-cache/

A

[1] As the name suggests, hibernate caches query data to make our application faster.
Hibernate Cache can be very useful in gaining fast application performance if used correctly.

The idea behind cache is to reduce the number of database queries, hence reducing the throughput time of the application. Hibernate first level cache is associated with the Session object.

Hibernate first level cache is enabled by default and there is no way to disable it. However hibernate provides methods through which we can delete selected objects from the cache or clear the cache completely. Any object cached in a session will not be visible to other sessions and when the session is closed, all the cached objects will also be lost.

[2] Hibernate first-level cache is used in 2 situations:
a) entityManager.find()
entityManager.find(1L, Author.class)
b) traverse a group of relationship
a.getBooks();

And it IS NOT USED for any other query (like JPQL, itp)!!!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is Second-Level Cache in Hibernate?

A

a second-level cache is SessionFactory-scoped, meaning it’s shared by all sessions created with the same session factory. When an entity instance is looked up by its id (either by application logic or by Hibernate internally, e.g. when it loads associations to that entity from other entities), and second-level caching is enabled for that entity, the following happens:

If an instance is already present in the first-level cache, it’s returned from there.
If an instance isn’t found in the first-level cache, and the corresponding instance state is cached in the second-level cache, then the data is fetched from there and an instance is assembled and returned.
Otherwise, the necessary data are loaded from the database and an instance is assembled and returned.
Once the instance is stored in the persistence context (first-level cache), it’s returned from there in all subsequent calls within the same session until the session is closed, or the instance is manually evicted from the persistence context. The loaded instance state is also stored in the L2 cache if it wasn’t already there.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the different states of an entity bean?

A

An entity bean instance can exist is one of the three states.
1. Transient: When an object is never persisted or associated with any session, it’s in transient state. Transient instances may be made persistent by calling save(), persist() or saveOrUpdate(). Persistent instances may be made transient by calling delete().

  1. Persistent: When an object is associated with a unique session, it’s in persistent state. Any instance returned by a get() or load() method is persistent.
  2. Detached: When an object is previously persistent but not associated with any session, it’s in detached state. An Object becomes detached when the currently running Persistence Context is closed. Any changes made to detached objects are no longer automatically propagated to the database.
    Once tx.commit() is executed, the student object becomes detached.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What will happen if we don’t have no-args constructor in Entity bean?

A

Hibernate uses Reflection API to create instance of Entity beans, usually when you call get() or load() methods. The method Class.newInstance() is used for this and it requires no-args constructor. So if you won’t have no-args constructor in entity beans, hibernate will fail to instantiate it and you will get HibernateException.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the collection types in Hibernate?

A

There are five collection types in hibernate used for one-to-many relationship mappings.
1. Bag
2. Set
3. List
4. Array
5. Map

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Can we execute native sql query in hibernate?

A

Hibernate provide option to execute native SQL queries through the use of SQLQuery object. For normal scenarios, it is however not the recommended approach because we loose benefits related to hibernate association and hibernate first level caching.

Also when we use native queries we loose possibility to validate if our query is valid (validate flag in spring configuration)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the benefit of native sql query support in hibernate?

A

Native SQL Query comes handy when we want to execute database specific queries that are not supported by Hibernate API such as query hints or the CONNECT keyword in Oracle Database.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the benefit of Hibernate Criteria API?

A

The primary advantage of Criteria query API is the possibility to build DYNAMIC CRITERIA QUERIES. For instance when we filter tables using different columns dynamically.

Hibernate provides Criteria API that is more object-oriented for querying the database and getting results. We can’t use Criteria to run the update or delete queries or any DDL statements. It’s only used to fetch the results from the database using a more object-oriented approach. Some of the common uses of Criteria API are:

  • Criteria API provides a Projection that we can use for aggregate functions such as sum(), min(), max() etc.
  • Criteria API can be used with ProjectionList to fetch selected columns only.
  • Criteria API can be used for join queries by joining multiple tables, useful methods are create alias(), setFetchMode() and set projection()
  • Criteria API can be used for fetching results with conditions, useful methods are added () where we can add Restrictions.
  • Criteria API provides add order() method that we can use for ordering the results.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is cascading and what are the different types of cascading?

A

Cascading allows propagating operation that is performed on the parent entity to children entities.
E.g. Person entity has an Address entity. When we remove a Person entity then it does not make sense to keep the Address entity. Instead, it should be removed.

When we have relationship between entities, then we need to define how the different operations will affect the other entity. This is done by cascading and there are different types of it.

Note that Hibernate CascadeType enum constants are little bit different from JPA javax.persistence.CascadeType, so we need to use the Hibernate CascadeType and Cascade annotations for mappings, as shown in above example. Commonly used cascading types as defined in CascadeType enum are:
1. None: No Cascading, it’s not a type but when we don’t define any cascading then no operations in parent affects the child.
2. ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist. Basically everything
3. SAVE_UPDATE: Cascades save and update, available only in hibernate.
4. DELETE: Corresponds to the Hibernate native DELETE action, only in hibernate.
5. DETATCH, MERGE, PERSIST, REFRESH and REMOVE - for similar operations
6. LOCK: Corresponds to the Hibernate native LOCK action.
7. REPLICATE: Corresponds to the Hibernate native REPLICATE action.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

[1] What is Hibernate N+1 problem?

A

Hibernate N+1 problem occurs when you use FetchType. LAZY for your entity associations. If you perform a query to select n-entities and if you try to call any access method of your entity’s lazy association, Hibernate will perform n-additional queries to load lazily fetched objects.

For example:
We have entity Book with relation one-to-many with entity Books.
If we try in persistent context get information about books then Hibernate will for every loaded author execute separate query to load Book from database. So for instance we have a query to load information about authors. Query returned us 100 authors. Now somewhere in the code we want to get information about author’s books. Hibernate then will execute 100 hundred separated queries to database to load information about book.

16
Q

How can you deal with Hibernate N+1 problem?

A

[1] Use JOIN FETCH when joining tables

entityManager.createQuery(“select a from Author a left join fetch a.books”, Author.class);

17
Q

What is the difference between first-level cache and second-level cache?

A

[1] First level cache is associated to Session object and cannot be shared between multiple sessions,

“Second level cache” is maintained at the Session Factory level and is shared among all sessions in Hibernate.

[2] “First level chance” is enabled by default and there is no way to disable it.
“Second level cache” is disabled by default, but we can enable it through configuration.

[3] “The first level cache” is available only until the session is open. Once the session is closed, the first-level cache is destroyed.

“The second level cache is available through the application’s life cycle, it is destroyed and recreated when an application is restarted.

18
Q

How can we make entities immutable in JPA/Hibernate?

A

By adding annotation @Immutable to the entity class we can make it immutable.

19
Q

[1] How does orphan Removal work with JPA and Hibernate?
[2] What is default orphan removal?

https://vladmihalcea.com/orphanremoval-jpa-hibernate/

A

Let’s say we have Post entity and its entity has many PostComments:

@OneToMany(
    mappedBy = "post",
    cascade = CascadeType.ALL,
    orphanRemoval = true
)
private List<PostComment> comments = new ArrayList<>();

When orphanRemoval is true and we remove one PostComment from list of postComments:

post.removeComment(post.getComments().get(0));

THEN this PostComment record is removed physically from Database:
DELETE FROM
post_comment
WHERE
id = 1

BUT if orpahnRemoval is true then PostComment is not removed from database but instead foreign key is set to NULL

UPDATE
post_comment
SET
post_id = NULL,
review = ‘Best book on JPA and Hibernate!’
WHERE
id = 1

20
Q

[1] What is the difference between a unidirectional and bidirectional relationship in JPA?

A

[1] A unidirectional relationship is a relation that one side does not know about the relation. In this relation, only one entity has a relationship field /property that refers to another entity.

In a Bidirectional relationship, each entity has a relationship field or property that refers to another entity. A bidirectional relationship provides navigational access in both directions so that you can access the other side without explicit queries.

21
Q

Describe rules that a Bidirectional relationship must follow for cases
1 - OneToMany
2- OneToOne
3-ManyTomany

A

[1] The inverse side of a bidirectional relationship must refer to its owning side(Entity which contains the foreign key) by using the mappedBy element of the @OneToOne, @OneToMany, or @ManyToMany annotation. The mappedBy element designates the property or field in the entity that is the owner of the relationship.

[2] The many side of @ManyToOne bidirectional relationships must not define the mappedBy element. The many side is always the owning side of the relationship.

[3] For @OneToOne bidirectional relationships, the owning side corresponds to the side that contains @JoinColumn i.e the corresponding foreign key.

[4] For @ManyToMany bidirectional relationships, either side may be the owning side.

22
Q

What is the difference between orphanRemoval and CascadeType.REMOVE?

A

if orpahnRemoval=true then parent entity and child entities are removed

if orphanRemoval=false then parent entity is removed and child entities update post_id foreign key to null.