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. |
Does Hibernate support Native SQL Queries? |
|
Answer» Yes, it does. HIBERNATE provides the createSQLQuery() METHOD to let a developer call the native SQL statement directly and returns a Query object. Consider the example where you want to get employee data with the full name “Hibernate”. We don’t want to use HQL-based features, instead, we want to write our own SQL QUERIES. In this case, the code would be: Query query = session.createSQLQuery( "select * from interviewbit_employee ibe where ibe.fullName = :fullName") .addEntity(InterviewBitEmployee.class) .setParameter("fullName", "Hibernate"); //named parametersList result = query.list();Alternatively, native queries can also be supported when USING NamedQueries. |
|
| 2. |
Can you tell the difference between setMaxResults() and setFetchSize() of Query? |
|
Answer» setMaxResults() the function works similar to LIMIT in SQL. Here, we set the maximum NUMBER of rows that we want to be returned. This method is implemented by all database drivers. setFetchSize() works for optimizing how Hibernate sends the result to the CALLER for example: are the RESULTS BUFFERED, are they sent in different SIZE chunks, etc. This method is not implemented by all the database drivers. |
|
| 3. |
Collection mapping can be done using One-to-One and Many-to-One Associations. What do you think? |
|
Answer» FALSE, COLLECTION MAPPING is POSSIBLE only with One-to-Many and Many-to-Many ASSOCIATIONS. |
|
| 4. |
When is merge() method of the hibernate session useful? |
|
Answer» Merge() method can be used for updating EXISTING values. The specialty of this method is, once the existing values are updated, the method creates a copy from the entity object and returns it. This RESULT object goes into the persistent context and is then tracked for any changes. The object that was INITIALLY used is not tracked. |
|
| 5. |
What is hibernate caching? |
|
Answer» Hibernate caching is the strategy for improving the application performance by pooling objects in the cache so that the queries are EXECUTED faster. Hibernate caching is particularly useful when fetching the same data that is executed multiple times. Rather than hitting the database, we can just access the data from the cache. This results in REDUCED throughput time of the application. Types of Hibernate CachingFirst Level Cache:
Second Level Cache:
|
|
| 6. |
What does session.lock() method in hibernate do? |
|
Answer» session.lock() method is used to REATTACH a detached object to the session. session.lock() method does not check for any data synchronization between the database and the object in the PERSISTENCE context and hence this reattachment MIGHT LEAD to loss of data synchronization. |
|
| 7. |
What are Many to Many associations? |
|
Answer» Many-to-many association INDICATES that there are multiple relations between the instances of two entities. We could take the example of multiple students taking part in multiple courses and vice versa. Since both the student and course entities refer to each other by MEANS of foreign keys, we represent this relationship TECHNICALLY by creating a separate table to HOLD these foreign keys. Many To Many AssociationsHere, Student-Course Table is called the Join Table where the student_id and course_id would form the composite primary key. |
|
| 8. |
Can you tell something about one to many associations and how can we use them in Hibernate? |
|
Answer» The one-to-many association is the most commonly used which indicates that one object is linked/associated with multiple objects. For example, one PERSON can own multiple cars. Hibernate One To Many MappingIn Hibernate, we can achieve this by using @OnetoMany of JPA ANNOTATIONS in the model classes. Consider the above example of a person having multiple cars as SHOWN below: @Entity@Table(name="Person")PUBLIC class Person { //... @OneToMany(mappedBy="owner") private Set<Car> cars; // getters and setters}In the Person class, we have defined the car's property to have @OneToMany association. The Car class would have owned property that is used by the mappedBy variable in the Person class. The Car class is as shown below: @Entity@Table(name="Car")public class Car { // Other Properties @ManyToOne @JoinColumn(name="person_id", nullable=false) private Person owner; public Car() {} // getters and setters}@ManyToOne annotation indicates that many INSTANCES of an entity are mapped to one instance of another entity – many cars of one person. |
|
| 9. |
What is HQL? |
|
Answer» Hibernate Query Language (HQL) is used as an extension of SQL. It is very simple, EFFICIENT, and very flexible for performing complex operations on relational databases without writing complicated queries. HQL is the object-oriented representation of query language, i.e instead of using table name, we MAKE use of the class name which makes this language independent of any database. This makes use of the Query interface provided by Hibernate. The Query object is obtained by calling the createQuery() method of the hibernate Session interface. Following are the most commonly used methods of query interface:
Example: To get a list of all records from InterviewBitEmployee Table: Query query=session.createQuery("from InterviewBitEmployee"); List<InterviewBitEmployee> list=query.list(); System.out.println(list.get(0)); |
|
| 10. |
What is criteria API in hibernate? |
|
Answer» Criteria API in Hibernate helps developers to build dynamic criteria queries on the persistence database. Criteria API is a more powerful and flexible alternative to HQL (Hibernate Query Language) queries for creating dynamic queries. This API allows to programmatically development criteria query objects. The org.hibernate.Criteria interface is used for these purposes. The Session interface of hibernate framework has createCriteria() METHOD that takes the persistent object’s class or its entity name as the parameters and returns persistence object instance the criteria query is executed. It also makes it very easy to incorporate restrictions to selectively retrieve data from the database. It can be achieved by using the add() method which accepts the org.hibernate.criterion.Criterion object representing individual restriction. Usage examples: To return all the data of InterviewBitEmployee entity class. Criteria criteria = session.createCriteria(InterviewBitEmployee.class);List<InterviewBitEmployee> results = criteria.list();To retrive objects whose property has value equal to the restriction, we use Restrictions.eq() method. For example, to fetch all records with name ‘Hibernate’: Criteria criteria= session.createCriteria(InterviewBitEmployee.class);criteria.add(Restrictions.eq("fullName","Hibernate"));List<InterviewBitEmployee> results = criteria.list();To get objects whose property has the value “not equal to” the restriction, we use Restrictions.ne() method. For example, to fetch all the records whose employee’s name is not Hibernate: Criteria criteria= session.createCriteria(InterviewBitEmployee.class);criteria.add(Restrictions.ne("fullName","Hibernate"));List<Employee> results = criteria.list()To retrieve all objects whose property matches a given PATTERN, we use Restrictions.like() (for CASE sensitivenes) and Restrictions.ilike()(for case insensitiveness) Criteria criteria= session.createCriteria(InterviewBitEmployee.class);criteria.add(Restrictions.like("fullName","Hib%",MatchMode.ANYWHERE));List<InterviewBitEmployee> results = criteria.list();Similarly, it also has other methods like isNull(), isNotNull(), gt(), ge(), lt(), le() etc for adding more varieties of restrictions. It has to be noted that for Hibernate 5 onwards, the functions returning an object of typeCriteria are deprecated. Hibernate 5 VERSION has provided interfaces like CriteriaBuilder and CriteriaQuery to serve the purpose: javax.persistence.criteria.CriteriaBuilderjavax.persistence.criteria.CriteriaQuery// Create CriteriaBuilderCriteriaBuilder builder = session.getCriteriaBuilder();// Create CriteriaQueryCriteriaQuery<YourClass> criteria = builder.createQuery(YourClass.class);For introducing restrictions in CriteriaQuery, we can use the CriteriaQuery.where method which is analogous to using the WHERE clause in a JPQL query. |
|
| 11. |
Differentiate between get() and load() in Hibernate session |
||||||||||
|
Answer» These are the methods to get data from the database. The primary DIFFERENCES between get and load in Hibernate are given below:
|
|||||||||||
| 12. |
Differentiate between save() and saveOrUpdate() methods in hibernate session. |
||||||||||
|
Answer» Both the methods save records to the table in the database in case there are no records with the primary key in the table. However, the main differences between these two are listed below:
Clearly, saveOrUpdate() is more flexible in terms of use but it involves extra processing to find out whether a record already exists in the table or not. |
|||||||||||
| 13. |
Can you tell the difference between getCurrentSession and openSession methods? |
||||||||||
|
Answer» Both the METHODS are provided by the Session Factory. The main differences are given below:
Apart from these two methods, there is another method openStatelessSession() and this method returns a stateless session object. |
|||||||||||
| 14. |
Explain Hibernate architecture |
|
Answer» The Hibernate architecture consists of MANY objects such as a persistent object, session factory, session, query, transaction, etc. Applications developed using Hibernate is MAINLY categorized into 4 parts:
The main elements of Hibernate framework are:
|
|
| 15. |
What are the most commonly used annotations available to support hibernate mapping? |
|
Answer» Hibernate framework provides support to JPA annotations and other useful annotations in the org.hibernate.annotations package. Some of them are as follows:
|
|
| 16. |
Explain hibernate mapping file |
|
Answer» Hibernate mapping file is an XML file that is used for defining the entity bean fields and corresponding database column mappings. In the previous example, we have defined the mapping resource as “InterviewBitEmployee.hbm.xml” in the config file. Let us SEE what that sample hbm.xml file looks like: <?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN""HTTP://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"><hibernate-mapping> <!-- What class is mapped to what database table--> <class name = "InterviewBitEmployee" table = "InterviewBitEmployee"> <meta attribute = "class-description"> This class CONTAINS the details of employees of InterviewBit. </meta> <ID name = "id" type = "INT" column = "employee_id"> <generator class="native"/> </id> <property name = "fullName" column = "full_name" type = "string"/> <property name = "email" column = "email" type = "string"/> </class></hibernate-mapping> |
|