JPA/Hibernate Flashcards
What is the difference between JPA and Hibernate?
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.
What are the advantages of Hibernate over JDBC?
[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
What is Hibernate SessionFactory?
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.
Is Hibernate SessionFactory thread safe?
Hibernate SessionFactory is thread safe?
What is Hibernate Session object?
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.
Is Hibernate Session object thread safe?
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.
[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/
[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)!!!
What is Second-Level Cache in Hibernate?
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.
What are the different states of an entity bean?
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().
- 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.
-
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.
What will happen if we don’t have no-args constructor in Entity bean?
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
.
What are the collection types in Hibernate?
There are five collection types in hibernate used for one-to-many relationship mappings.
1. Bag
2. Set
3. List
4. Array
5. Map
Can we execute native sql query in hibernate?
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)
What is the benefit of native sql query support in hibernate?
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.
What is the benefit of Hibernate Criteria API?
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.
What is cascading and what are the different types of cascading?
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.