JPA and Hibernate

Ace your homework & exams now with Quizwiz!

What ORM is ?

ORM - object relational mapping. Map object to DB.

Different between session.get() and session.load() ?

1. session.load() - It will always return a "proxy" (Hibernate term) without hitting the database. In Hibernate, proxy is an object with the given identifier value, its properties are not initialized yet, it just look like a temporary fake object. - If no row found , it will throws an ObjectNotFoundException. 2. session.get() - It always hit the database and return the real object, an object that represent the database row, not proxy. If no row found , it return null.

@PersitenceContext vs @Autowired

@PersistenceContext: - does not return entity manager instance It returns container-managed proxy that acquires and releases presistance context on behalf of the application code

What is the difference between Set, Bag and List in Hibernate ?

A <bag> is an unordered collection, which can contain duplicated elements. That means if you persist a bag with some order of elements, you cannot expect the same order retains when the collection is retrieved. There is not a "bag" concept in Java collections framework, so we just use a java.util.List corresponds to a <bag>. A <set> is similar to <bag> except that it can only store unique objects. That means no duplicate elements can be contained in a set. When you add the same element to a set for second time, it will replace the old one. A set is unordered by default but we can ask it to be sorted. The corresponding type of a in Java is java.util.Set.

When lazyLoadingInitialization Exception could occur ?

A LAZY association is exposed via a Proxy, which allows the data access layer to load the association on demand. Unfortunately, LAZY associations can lead to LazyInitializationException. Hibernate is going to throw a LazyInitializationException because the PostComment entity did not fetch the Post association while the EntityManager was still opened, and the Post relationship was marked with FetchType.LAZY. How to solve if you need update data: Entities are only needed when the current running application-level transaction needs to modify the entities that are being fetched. Because of the automatic dirty checking mechanism, Hibernate makes it very easy to translate entity state transitions into SQL statements. Considering that we need to modify the PostComment entities, and we also need the Post entities as well, we just need to use the JOIN FETCH directive For select: Now, we are not done yet. What if you don't even want entities in the first place. If you don't need to modify the data that's being read, why would you want to fetch an entity in the first place? A DTO projection allows you to fetch fewer columns and you won't risk any LazyInitializationException.

What are the hibernate strategies for generate primary keys (Generated Ids) ?

AUTO: Hibernate selects the generation strategy based on the used dialect, IDENTITY: Hibernate relies on an auto-incremented database column to generate the primary key, SEQUENCE: Hibernate requests the primary key value from a database sequence, TABLE: Hibernate uses a database table to simulate a sequence. https://www.thoughts-on-java.org/jpa-generate-primary-keys/

What is the purpose of AccessType.FIELD, AccessType.PROPERTY and @Access

AccessType.PROPERTY: Access property of the class by using getters and setters.(Person.getId()) AccessType.FIELD: Access property of the class directly (Person.id) Field access in Hibernate - It is good to know that while field access is OK for Hibernate to populate your entities, your code should still access those values through methods. Otherwise you will fall into the first of the Hibernate proxy pitfalls mentioned by my colleague Maarten Winkels.

What is the difference between Bag and IdBag?

Bag is an unordered collection, and, unlike idbag, it doesn't use an extra column for storing each element index. The only difference is their efficiency: Bags are the most efficient inverse collection but they perform poorly for unidirectional one-to-many associations: Bags are the worst case since they permit duplicate element values and, as they have no index column, no primary key can be defined. Hibernate has no way of distinguishing between duplicate rows. Hibernate resolves this problem by completely removing in a single DELETE and recreating the collection whenever it changes. This can be inefficient. idbag are a legacy hibernate mapping and they were used to provide a more efficient unidirectional associations alternative

First-level Cache vs Second-level Cache vs Query-level Cache

First-level Cache The first-level cache is the Session cache and is a mandatory cache through which all requests must pass. The Session object keeps an object under its own power before committing it to the database. If you issue multiple updates to an object, Hibernate tries to delay doing the update as long as possible to reduce the number of update SQL statements issued. If you close the session, all the objects being cached are lost and either persisted or updated in the database. Second-level Cache Second level cache is an optional cache and first-level cache will always be consulted before any attempt is made to locate an object in the second-level cache. The second level cache can be configured on a per-class and per-collection basis and mainly responsible for caching objects across sessions. Any third-party cache can be used with Hibernate. An org.hibernate.cache.CacheProvider interface is provided, which must be implemented to provide Hibernate with a handle to the cache implementation. Query-level Cache Hibernate also implements a cache for query resultsets that integrates closely with the second-level cache. This is an optional feature and requires two additional physical cache regions that hold the cached query results and the timestamps when a table was last updated. This is only useful for queries that are run frequently with the same parameters.

Inheritance strategies with JPA and Hibernate

JPA and Hibernate support 4 inheritance strategies which map the domain objects to different table structures. Mapped Superclass The mapped superclass strategy is the simplest approach to mapping an inheritance structure to database tables. It maps each concrete class to its own table. Table per Class The table per class strategy is similar to the mapped superclass strategy. The main difference is that the superclass is now also an entity. Each of the concrete classes gets still mapped to its own database table. This mapping allows you to use polymorphic queries and to define relationships to the superclass. But the table structure adds a lot of complexity to polymorphic queries, and you should, therefore, avoid them. Single Table The single table strategy maps all entities of the inheritance structure to the same database table. This approach makes polymorphic queries very efficient and provides the best performance.But it also has some drawbacks. The attributes of all entities are mapped to the same database table. Each record uses only a subset of the available columns and sets the rest of them to null. Joined The joined table approach maps each class of the inheritance hierarchy to its own database table. This sounds similar to the table per class strategy. But this time, also the abstract superclass Publication gets mapped to a database table. This table contains columns for all shared entity attributes. The tables of the subclasses are much smaller than in the table per class strategy. They hold only the columns specific for the mapped entity class and a primary key with the same value as the record in the table of the superclass.

What JPA is ?

Java persistance API

Difference between Optimistic Locking & Pessimistic Locking ?

Optimistic Locking :- In this locking, multiple users can open the same record for updating, thus increase maximum concurrency. Record is only locked when updating the record. This is the most preferred way of locking practically. Please note that, Optimistic lock is an implicit lock. In Hibernate, we can achieve optimistic control with versioning. Version checking uses version numbers, or timestamps, to detect conflicting updates and to prevent lost updates. Hibernate provides three possible approaches to write application code that uses optimistic concurrency. Pessimistic Locking :- In this locking, when the user wants to update data it locks the record and till then no one can update data. Other user's can only view the data when there is pessimistic locking. As we can see, now a days in browser based application it is very common and having pessimistic locking is not a practical solution at all. This is often done by relying on the database itself and most relational databases use this method. Please note that, Pessimistic lock is an explicit lock that set by the client. In Hibernate, we can achieve pessimistic control with the mechanism of Database. To use pessimistic locking you need either a direct connection to the database or an externally available transaction ID that can be used independently of the connection.

What are proxies in Hibernate?

Proxies are the mechanism that allows Hibernate to break up the interconnected cloud of objects in the database into smaller chunks, that can easily fit in memory.

Concurrency in Hibernate object. Is SessionFactory or Session tread safe ?

Session factory objects are to be implemented using the singleton design pattern. Instances of SessionFactory are thread-safe and typically shared throughout an application. As these objects are heavy weight because they contains the connection information, hibernate configuration information and mapping files,location path. So creating number of instances will make our application heavy weight. But the session objects are not thread safe. So in short it is - SessionFactory objects are one per application and Session objects are one per client. Hence it would be one SessionFactory per DataSource. Your application may have more than one DataSource so you may have more than one SessionFactory in that instance. But you would not want to create a SessionFactory more than once in an application. Advantages: Obviously its improving performance of your application :) 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 vs. EntityManagerFactory

SessionFactory - SessionFactory and Session are hibernate-specific. EntityManagerFactory - invokes the hibernate session under the hood. And if you need some specific features that are not available in the EntityManager Here, there is two opinions are popular: 1. EntityManagerFactory is the standard implementation, it is the same across all the implementations. If we migrate our ORM for any other provider, there will not be any change in the approach for handling the transaction. In contrast, if you use hibernate's session factory, it is tied to hibernate APIs and ca not migrate to new vendor easily. 2. One dis-advantage of using the standard implementation is that, it is not providing the advanced features. There is not much control provided in the EntityManager APIs. Whereas, hibernate's SessionFactory has lot of advanced features which can not done in JPA. One such thing is retrieving the ID generator without closing the transaction, batch insert, etc.

GenerationType.AUTO

The GenerationType.AUTO is the default generation type and lets the persistence provider choose the generation strategy.

GenerationType.IDENTITY

The GenerationType.IDENTITY is the easiest to use but not the best one from a performance point of view. It relies on an auto-incremented database column and lets the database generate a new value with each insert operation. From a database point of view, this is very efficient because the auto-increment columns are highly optimized, and it doesn't require any additional statements. This approach has a significant drawback if you use Hibernate. Hibernate requires a primary key value for each managed entity and therefore has to perform the insert statement immediately. This prevents it from using different optimization techniques like JDBC batching.

GenerationType.SEQUENCE

The GenerationType.SEQUENCE is my preferred way to generate primary key values and uses a database sequence to generate unique values. It requires additional select statements to get the next value from a database sequence. But this has no performance impact for most applications. And if your application has to persist a huge number of new entities, you can use some Hibernate specific optimizations to reduce the number of statements.

GenerationType.TABLE

The GenerationType.TABLE gets only rarely used nowadays. It simulates a sequence by storing and updating its current value in a database table which requires the use of pessimistic locks which put all transactions into a sequential order. This slows down your application, and you should, therefore, prefer the GenerationType.SEQUENCE, if your database supports sequences, which most popular databases do.

Why @PersitenceContext annotation is used for ?

This annotation is used for injecting EntityManager bean into classes.

What are the types of Hibernate instance states?

Transient An object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session. It has no persistent representation in the database and no identifier value has been assigned. Transient instances will be destroyed by the garbage collector if the application does not hold a reference anymore. Use the Hibernate Session to make an object persistent (and let Hibernate take care of the SQL statements that need to be executed for this transition). Persistent A persistent instance has a representation in the database and an identifier value. It might just have been saved or loaded; however, it is by definition in the scope of a Session. Hibernate will detect any changes made to an object in persistent state and synchronize the state with the database when the unit of work completes. Developers do not execute manual UPDATE statements, or DELETE statements when an object should be made transient. Detached A detached instance is an object that has been persistent, but its Session has been closed. The reference to the object is still valid, of course, and the detached instance might even be modified in this state. A detached instance can be reattached to a new Session at a later point in time, making it (and all the modifications) persistent again. This feature enables a programming model for long running units of work that require user think-time. We call them application transactions, i.e., a unit of work from the point of view of the user.

Difference between update vs merge ?

Update: When we call update() method on session, if that session doesn't contains same object (provided in update()) in cache then update() method successfully executed and the object been converted detached state to persistent state. When we call update() method, if already a session cache containing the same object then the update() method throws an exception called NonUniqueObjectException. MERGE: Like update() method merge is also used to transfer an object from detached stated to persistent state. If we call merge() method, then it verifies whether the same object is existed in the cache or not. If the object is existed in the cache then changes are copied in to the cache. other wise it will load the values to cache. Hence it doesn't throw any exception. Difference: When we call update() method, if the object already existed in cache update() method will throw exception where as merge() method copies the changes in to cache.

Association Mappings with JPA and Hibernate

one-to-one associations, many-to-one associations and many-to-many associations. You can map each of them as a uni- or bidirectional association. That means you can either model them as an attribute on only one of the associated entities or on both. That has no impact on your database mapping, but it defines in which direction you can use the relationship in your domain model and JPQL or Criteria queries.


Related study sets

Indiana Life Insurance Exam Prep

View Set

Marketing 301 Questions from Concept Checks Chap 16-19

View Set

Chapter 02 Quiz: Biology and Psychology

View Set

Seminole - 3rd 6 Weeks Test Review

View Set

[Exam 4] Pediatrics: Endocrine and Genitourinary Practice Question

View Set

11,13,14,15,16,17 Quiz Review PHY1020C

View Set