Hibernate Interview Questions And Answers

Question: What are 3 states of instances of any persistent class?
Answer:

Instances may exist in one of the following three states at a given point in time −

  • transient − A new instance of a persistent class, which is not associated with a Session and has no representation in the database and no identifier value is considered transient by Hibernate.

  • persistent − You can make a transient instance persistent by associating it with a Session. A persistent instance has a representation in the database, an identifier value and is associated with a Session.

  • detached − Once we close the Hibernate Session, the persistent instance will become a detached instance.


Question: Explain SessionFactory Object
Answer
           1.    Configuration object is used to create a SessionFactory object
          2.   The SessionFactory is a thread safe object and used by all the threads of an application.
          3.   The SessionFactory is a heavyweight object; it is usually created during application                        start up and kept for later use. You would need one SessionFactory object per                                database using a separate configuration file. So, if you are using multiple databases,                      then you would have to create multiple SessionFactory objects.

Question: Explain Session Object
Answer
           1.     A Session is used to get a physical connection with a database.
          2.   The Session object is lightweight and designed to be instantiated each time an interaction is needed with the database..
          3.   Persistent objects are saved and retrieved through a Session object.
          4.  Session object is not thread safe.
          5. A Session instance is serializable if its persistent classes are serializable.
          6. Session is an interface in hibernate.

Question: how many generators in hibernate?

Answer
             1. Native 
             2. identity
           3. Sequence
           4. HILO

Question: Explain all annotation in hibernate?
Answer
             1. @Entity - This is used to mark pojo class as Entity bean so it must have a no-argument constructor that is visible with at least protected scope.

             2. @Table The @Table annotation allows you to specify the details of the table that will be used to persist the entity in the database.

                       The @Table annotation provides four attributes, allowing you to override the name of the table, its catalogue, and its schema, and enforce unique constraints on columns in the table. 

           3. @Id and @GeneratedValue Annotations

Each entity bean will have a primary key, which you annotate on the class with the @Id annotation. The primary key can be a single field or a combination of multiple fields depending on your table structure.

By default, the @Id annotation will automatically determine the most appropriate primary key generation strategy to be used but you can override this by applying the @GeneratedValue annotation, which takes two parameters strategy and generator

           4. @Column Annotation

Question: Differences between set, list and bag collection in hibernate?

  • Set - No duplicates and No order
  • Bag - Can contain Duplicates and No Order (Also called, Unordered List or Set with duplicates). we can specify ordering either natural or by implementing comparable/comparator class implementation.           By specifying it's order-by attribute, its elements will be ordered as part of SELECT:

  • <bag name="trips" cascade="all" order-by="scheduledDate">
        <key column="trainId"/>
        <one-to-many class="Trip"/>
    </bag> 
Note that order-by attribute needs to specify column name(s), not property name. The above can be mapped to java.util.List, you can do the same with java.util.Set by using <set> mapping.
  • List - Can contain Duplicates but with Order preserved

    • Can be created using @OrderBy to preserve order

Performance Antipatterns of One To Many Association in Hibernate https://fedcsis.org/proceedings/2013/pliks/322.pdf

in short:

  • Bag semantics -> List / Collection + @OneToMany ->                                                              One Element Added:      1 delete, N inserts                                                                                    One Element Removed: 1 delete, N inserts
  • List semantics -> List + @OneToMany + @IndexColumn / @OrderColumn ->                            One Element Added:      1 insert, M updates                                                                                  One Element Removed: 1 delete, M updates
  • Set semantics -> Set + @OneToMany ->                                                                                    One Element Added: 1 insert                                                                                                      One Element Removed: 1 delete


Question: explain Second-level Cache in hibernate?
Answer:

Question: Which are the design patterns used in Hibernate?
Answer: 


            1.    Domain Model Pattern – An object model of the domain that incorporates both behavior and data.
            2.    Proxy Pattern for lazy loading.
            3.    Unit of Work (as part of Session object)
            4.    Factory Pattern in Session Factory
            5.    Query Object for Criterion API
            6.    Data Mapper – A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper itself.
            7.    Active Record Pattern
            8.    DAO
            9.    Object-Relational Mapping(ORM)
QuestionWhat are the different approaches to represent an inheritance hierarchy?
Answer : 
  1. Table per concrete class.
  2. Table per class hierarchy.
  3. Table per subclass.
Question: What is Implicit Polymorphism in Hibernate?
Answer: 


            1.    Implicit polymorphism in Hibernate is one of the inheritance strategies supported in Hibernate. 
            2.    Implicit polymorphism means if a class or interface is used in HQL, criteria or named queries, hibernate fetches the records from the table mapped to the used class along with all the tables mapped to its subclasses, at any hierarchy level. 

            3.   
HibernateImplicitPolymorphism-diag




Here we have implemented the mapping using table per concrete class approach, where CashPayment class is mapped to CASHPAYMENT table and CardPayment table is mapped to CARDPAYMENT table.
If we want to retrieve the list of all the payments made via cash or card, below query would do the magic.

session.createCriteria(Payment.class).list();
While processing this criteria query, hibernate perform following operations –

  • Identify all the subclasses of payment, which are mapped to any table
  • Fire individual query to all of the tables
  • Combine the result of all the queries into list and return from hibernate layer
For more info https://javabeat.net/implicit-polymorphism-hibernate/


Question: What is Explicit Polymorphism in Hibernate?
Answer:


In your case, if Entity Class Nodes were not mapped and Persons were having polymorphism explicit, then Nodes would not return Persons elements.
Look at this code..
public class Node implements Serializable {
    ...
}



@Entity
@Polymorphism(type= PolymorphismType.EXPLICIT)
@Table(name="Persons")
public class Person extends Node {
}


@Entity
@Polymorphism(type= PolymorphismType.EXPLICIT)
@Table(name="Networks")
public class Network extends Node {
}

To hide the subclasses, you will have to annotate the subclasses with EXPLICIT and not the base class.
If the parent class was not mapped (e.g. being annotated with @Entity) and the sub-classes were having explicit polymorphism, then querying for super-class would not return the sub-class.
Question: Why Serialization is required in Hibernate?
Answer
           1.     If we just talk about persistence, Serializable is not needed even not in Hibernate/JPA
          2.   But EntityBean in EJB should be Serializable since it is used in remote communication.
          3.   if we want to store same domain/entiry class in the HttpSession then it must implements Serializable.
          4. if you implement second-level cache in hibernate then your class should be Serializable.

Question:  Explain @Immutable in Hibernate

Question:  Explain JPA @Embedded And @Embeddable  in Hibernate


Question:  final class impact  in Hibernate

Question:  Session.save() vs Session.saveOrUpdate() vs Session.Persist

Answer:

1) The main difference between save() and saveOrUpdate() method is that save() method performs an INSERT operation to store the object into the database, but INSERT will fail if the primary key is already persistent i.e. object already exists in the database. This is why, you should only call save() with an absolutely new object which doesn't have any database identifier. Calling save() with the detached object will fail. This is opposite of saveOrUpdate() method, which can do either INSERT or UPDATE SQL query depending upon whether an object exists in the database or not. The saveOrUpdate() method first executes a SELECT query to determine if it needs to do an INSERT or UPDATE operation.


2) Another key difference between save() and saveOrUpdate() method is that former is used to bring a transient object to persistent state but saveOurUpdate() can bring both transient (new) and detached (existing) object into persistent state. It is often used to re-attach a detached object into Session.

Here is an object's lifecycle and state transition diagram in Hibernate which shows that save() and saveOrUpdate() can move an object from transient to persistent state.




3) Coming to persist() method, the difference between save() and persist() method is that former returns the generated database identifier, a Serializable object but persist() method doesn't return anything. It's return type is void.

For example:
System.out.println(session.save(aCoin));

will print the generated primary key, but the following line will throw a compile time error because persist()'s return type is void.

System.out.println(session.persist(aCoin));


Question: Difference between SessionLock and SessionUpdate?

Question: What is optimistic and pessimistic locking in hibernate?

Question: one-to-many lazy load in hibernate

Question: 


What do you understand by Distributed Transaction?
Distributed Transaction is any situation where a single event results in the mutation of two or more separate sources of data which cannot be committed atomically. In the world of microservices, it becomes even more complex as each service is a unit of work and most of the time multiple services have to work together to make a business successful.

what is n+1 problem and how do you resolve it?

https://vladmihalcea.com/n-plus-1-query-problem/

FetchType.EAGER

Using FetchType.EAGER either implicitly or explicitly for your JPA associations is a bad idea because you are going to fetch way more data that you need. More, the FetchType.EAGER strategy is also prone to N+1 query issues.

Unfortunately, the @ManyToOne and @OneToOne associations use FetchType.EAGER by default, so if your mappings look like this:

Auditing with JPA, Hibernate, and Spring Data JPA?











    SHARE

    esant technology

    0 comments :

    Post a Comment