InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
What are the benefits of NamedQuery? |
|
Answer» In order to understand the benefits of NamedQuery, let's first understand the disadvantage of HQL and SQL. The main disadvantage of having HQL and SQL scattered across data access objects is that it makes the code unreadable. Hence, as good practice, it is recommended to group all HQL and SQL codes in ONE place and use only their reference in the actual data access code. In order to achieve this, Hibernate gives US NAMED queries. A named query is a statically defined query with a predefined unchangeable query string. They are validated when the session factory is created, THUS making the application fail fast in case of an error. ConclusionHibernate is the most powerful open source ORM tool that is used for mapping java objects with the database structures at run time. It has become more popular among software DEVELOPERS due to its nature of abstraction allowing developers to continue application development by being database independent and focus just on the application business logic. Additional Resources Practice Coding Java Tutorials Java Interview Questions |
|
| 2. |
Can you tell something about Named SQL Query |
|
Answer» A named SQL query is an expression represented in the form of a table. Here, SQL expressions to select/retrieve rows and columns from one or more tables in one or more DATABASES can be specified. This is like using aliases to the queries. In hibernate, we can make use of @NameQueries and @NameQuery annotations.
Code Snippet: We can define Named Query as shown below @NamedQueries( { @NamedQuery( name = "findIBEmployeeByFullName", query = "from InterviewBitEmployee e where e.fullName = :fullName" ) } ):fullName REFERS to the parameter that is programmer defined and can be set using the query.setParameter method while using the named query. Usage: TypedQuery query = session.getNamedQuery("findIBEmployeeByFullName"); query.setParameter("fullName","Hibernate"); List<InterviewBitEmployee> ibEmployees = query.getResultList();The getNamedQuery method TAKES the name of the named query and returns the query instance. |
|
| 3. |
Can you tell something about Table Per Class Strategy. |
|
Answer» Table Per Class Strategy is another type of inheritance mapping strategy where each class in the hierarchy has a corresponding mapping database table. For example, the InterviewBitContractEmployee class details are stored in the interviewbit_contract_employee table and InterviewBitPermanentEmployee class details are stored in interviewbit_permanent_employee tables respectively. As the data is stored in different tables, there will be no need for a discriminator column as done in a single table strategy. Hibernate provides @Inheritance annotation which takes strategy as the parameter. This is used for defining what strategy we would be USING. By giving them value, InheritanceType.TABLE_PER_CLASS, it signifies that we are using a table per class strategy for mapping. The code snippet will be as shown below: InterviewBitEmployee class: @Entity(name = "interviewbit_employee")@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)@NoArgsConstructor@AllArgsConstructorpublic class InterviewBitEmployee { @Id @Column(name = "employee_id") private String employeeId; private String fullName; private String email;}InterviewBitContractEmployee class: @Entity(name = "interviewbit_contract_employee")@Table(name = "interviewbit_contract_employee")@NoArgsConstructor@AllArgsConstructorpublic class InterviewBitContractEmployee EXTENDS InterviewBitEmployee { private LocalDate contractStartDate; private LocalDate contractEndDate; private String agencyName;}InterviewBitPermanentEmployee class: @Entity(name = "interviewbit_permanent_employee")@Table(name = "interviewbit_permanent_employee")@NoArgsConstructor@AllArgsConstructorpublic class InterviewBitPermanentEmployee extends InterviewBitEmployee { private LocalDate workStartDate; private int numberOfLeaves;}Disadvantages: |
|
| 4. |
What is Single Table Strategy? |
|
Answer» Single Table Strategy is a hibernate’s strategy for PERFORMING inheritance mapping. This strategy is considered to be the best among all the other existing ones. Here, the inheritance data hierarchy is stored in the single table by making use of a discriminator column which determines to what class the record belongs. For the example defined in the Hibernate Inheritance Mapping question above, if we follow this single table strategy, then all the permanent and contract employees’ details are stored in only one table called InterviewBitEmployee in the database and the employees would be differentiated by making use of discriminator column named employee_type. Hibernate provides @Inheritance annotation which takes strategy as the PARAMETER. This is used for defining what strategy we would be using. By GIVING them value, InheritanceType.SINGLE_TABLE signifies that we are using a single table strategy for mapping.
The code snippet would be like this: InterviewBitEmployee class: @Entity@Table(name = "InterviewBitEmployee")@Inheritance(strategy = InheritanceType.SINGLE_TABLE)@DiscriminatorColumn(name = "employee_type")@NoArgsConstructor@AllArgsConstructorpublic class InterviewBitEmployee { @Id @Column(name = "employee_id") PRIVATE String employeeId; private String fullName; private String email;}InterviewBitContractEmployee class: @Entity@DiscriminatorValue("contract")@NoArgsConstructor@AllArgsConstructorpublic class InterviewBitContractEmployee extends InterviewBitEmployee { private LocalDate contractStartDate; private LocalDate contractEndDate; private String agencyName;}InterviewBitPermanentEmployee class: @Entity@DiscriminatorValue("permanent")@NoArgsConstructor@AllArgsConstructorpublic class InterviewBitPermanentEmployee extends InterviewBitEmployee { private LocalDate workStartDate; private int numberOfLeaves;} |
|
| 5. |
What are the concurrency strategies available in hibernate? |
|
Answer» Concurrency STRATEGIES are the MEDIATORS responsible for storing and retrieving items from the cache. While enabling second-level cache, it is the responsibility of the developer to PROVIDE what strategy is to be IMPLEMENTED to decide for each persistent class and collection. Following are the concurrency strategies that are used:
|
|
| 6. |
How to solve N+1 SELECT problem in Hibernate? |
|
Answer» Some of the strategies followed for solving the N+1 SELECT PROBLEM are: |
|
| 7. |
Can you tell something about the N+1 SELECT problem in Hibernate? |
|
Answer» N+1 SELECT problem is due to the result of using lazy loading and on-demand fetching STRATEGY. Let's take an example. If you have an N items list and each item from the list has a DEPENDENCY on a collection of another object, say bid. In order to FIND the highest bid for each item while using the lazy loading strategy, hibernate has to first fire 1 query to load all items and then subsequently fire N QUERIES to load big of each item. HENCE, hibernate actually ends up executing N+1 queries. |
|
| 8. |
Explain Query Cache |
|
Answer» Hibernate framework provides an optional feature called CACHE region for the queries’ resultset. Additional configurations have to be done in code in order to enable this. The query cache is USEFUL for those queries which are most frequently called with the same parameters. This increases the speed of the data retrieval and greatly improves performance for commonly repetitive queries. This does not cache the STATE of actual entities in the result set but it only stores the identifier VALUES and results of the value type. Hence, query cache should be always used in association with second-level cache. Configuration: In the hibernate configuration XML file, set the use_query_cache property to true as shown below: <property name="hibernate.cache.use_query_cache">true</property>In the code, we need to do the below CHANGES for the query object:Query query = session.createQuery("from InterviewBitEmployee");query.setCacheable(true);query.setCacheRegion("IB_EMP"); |
|
| 9. |
What are the states of a persistent entity? |
|
Answer» A persistent ENTITY can exist in any of the following states: Transient:
Persistent:
Following methods can be used upon the persistence object: session.save(record); session.persist(record); session.update(record); session.saveOrUpdate(record); session.lock(record); session.merge(record);Detached:
The object enters this state whenever any of the following methods are CALLED: session.close();session.clear();session.detach(record);session.evict(record);Persistent Entity |
|
| 10. |
Can we declare the Entity class final? |
|
Answer» No, we should not define the ENTITY CLASS FINAL because hibernate USES proxy classes and objects for lazy loading of data and hits the database only when it is absolutely needed. This is achieved by extending the entity bean. If the entity class (or bean) is made final, then it cant be extended and hence lazy loading can not be supported. |
|
| 11. |
What happens when the no-args constructor is absent in the Entity bean? |
|
Answer» Hibernate framework INTERNALLY uses Reflection API for creating entity bean instances when GET() or load() METHODS are called. The method Class.newInstance() is used which requires a no-args constructor to be PRESENT. When we don't have this constructor in the entity beans, then hibernate fails to instantiate the bean and hence it throws HibernateException. |
|