Using Hibernate SQL Dialects, we can switch databases. Hibernate generates appropriate HQL queries based on the dialect defined.
Posted Date:- 2021-08-21 09:27:10
The benefits of using the Hibernate Template are :
The Spring Template class simplifies interactions with the Hibernate Session.
The common functions are simplified to single method calls.
The sessions are automatically closed.
All exceptions are automatically caught and converted to runtime exceptions.
Posted Date:- 2021-08-21 09:26:26
Usually we define Sequence Generated using <generator> tag.
<id column=â€USER_IDâ€ name=â€idâ€ type=â€java.lang.Longâ€>
Posted Date:- 2021-08-21 09:24:37
First we need to write Java domain objects (beans with setter and getter). Write hbm.xml, where we map java class to table and database columns to Java class variables.
<class name=â€com.test.Userâ€ table=â€userâ€>
<property column=â€USER_NAMEâ€ length=â€255â€³
name=â€userNameâ€ not-null=â€trueâ€ type=â€java.lang.Stringâ€/>
<property column=â€USER_PASSWORDâ€ length=â€255â€³
name=â€userPasswordâ€ not-null=â€trueâ€ type=â€java.lang.Stringâ€/>
Posted Date:- 2021-08-21 09:23:20
The Session Interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects.
Session session = sessionFactory.openSession();
Posted Date:- 2021-08-21 09:21:34
The most common methods of Hibernate configuration are: Programmatic configuration and XML configuration (hibernate.cfg.xml).
Posted Date:- 2021-08-21 09:20:44
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects.
Posted Date:- 2021-08-21 09:20:05
When we have relationship between entities, 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 different from JPA javax.persistence.CascadeType, so we need to use the Hibernate CascadeType and Cascade annotations for mappings.
Commonly used cascading types as defined in CascadeType enum are:
None:This is not a type but when we donâ€™t define any cascading then no operations in parent affects the child.
ALL:Cascades save, delete, update, evict, lock, replicate, merge, and persist.
SAVE_UPDATE:Cascades save and update, available only in Hibernate.
DELETE:Corresponds to the Hibernate native DELETE action, only in Hibernate.
DETATCH, MERGE, PERSIST, REFRESH and REMOVE â€“ They have similar operations.
LOCK:This corresponds to the Hibernate native LOCK action.
REPLICATE:This corresponds to the Hibernate native REPLICATE action.
Posted Date:- 2021-08-21 09:19:20
Hibernate provides option to execute native SQL queries through the use of SQLQuery object. For normal scenarios, this is not the recommended approach because we lose benefits related to Hibernate association and Hibernate first level caching.
Posted Date:- 2021-08-21 09:17:05
Hibernate use proxy classes for lazy loading of data, only when itâ€™s needed. This is done by extending the entity bean, if the entity bean will be final then lazy loading will not be possible, hence low performance.
Posted Date:- 2021-08-21 09:14:51
The internal state of SessionFactory is immutable, so itâ€™s thread safe. Multiple threads can access it simultaneously to get Session instances.
Posted Date:- 2021-08-21 09:13:35
The plugin helps developers to write and manage their files in a much easier manner when compared to default Hibernate methods.
Posted Date:- 2021-08-21 09:11:30
One of the more expansive Hibernate interview questions, in total there are three object states - detached, persistent and transient.
Objects become detached once the session is closed by the developer. Detached objects can then turn into persistent ones, with proper methods enabled. Persistent objects are those who are open - they happen whenever you save or retrieve certain instances from the Hibernate database. Transient objects are the â€œodd onesâ€ - they are objects that have just been created, and are yet to be distinguished by a specific Session.
Posted Date:- 2021-08-21 09:10:13
Although this can be seen as one of the more subjective Hibernate interview questions, your employers are most likely trying to find out if you know the general pros of using Hibernate templates.
Posted Date:- 2021-08-21 09:08:59
The two collections of Hibernate are Sorted and Order.
Posted Date:- 2021-08-21 09:07:57
The user can use extension interfaces to add any required functionality that is not supported by built-in ones.
Posted Date:- 2021-08-21 09:06:02
All of the mapping documents of Hibernate are located within what is known as the Configuration Interface. This interface is used to both stores the before mentioned documents and issue-specific configuration commands to the framework itself.
You could go as far as to say that this could be viewed as one of the tricks Hibernate interview questions. Most employers would ask you something in the lines of â€œWhat is the Configuration Interface used for in Hibernate?â€. However, the question above is concerned with the actual functions of the interface - you have to know the Configuration Interface to be able to answer swiftly and correct. So, be on the lookout of similar questions!
Posted Date:- 2021-08-21 09:04:59
Criteria is a powerful API that is simple to use and which is used to retrieve entities through criteria object composition.
Posted Date:- 2021-08-21 09:03:46
Transient state: New objects are created in the Java program but are not associated with any Hibernate Session.
Persistent state: An object which is associated with a Hibernate session is called Persistent object. While an object which was earlier associated with Hibernate session but currently itâ€™s not associate is known as a detached object. You can call save() or persist() method to store those object into the database and bring them into the Persistent state.
Detached state: You can re-attach a detached object to Hibernate sessions by calling either update() or saveOrUpdate() method.
Posted Date:- 2021-08-21 09:01:56
sorted collection sort the data in JVMâ€™s heap memory using Javaâ€™s collection framework sorting methods. The ordered collection is sorted using order by clause in the database itself.
Posted Date:- 2021-08-21 09:00:42
This is one of the most frequently asked Hibernate Interview Questions. The key difference between the get() and load() method is:
load(): It will throw an exception if an object with an ID passed to them is not found.
get(): Will return null.
load(): It can return proxy without hitting the database unless required.
get(): It always goes to the database.
So sometimes using load() can be faster than the get() method.
Posted Date:- 2021-08-21 08:59:57
In order to view the SQL on a console, you need to add following in Hibernate configuration file to enable viewing SQL on the console for debugging purposes:
Posted Date:- 2021-08-21 08:58:39
Yes, you can create SQL queries in Hibernate. To create an SQL query, you must use the following syntax:
Posted Date:- 2021-08-21 08:55:18
Java Persistence API (JPA) is a specification that allocates standards and functionalities to ORM tools. You can access JPA classes and interfaces from the javax.persistence package. All JPA specifications are defined using annotations in the javax.persistence package. The advantage of using JPA annotations is that they allow you to write implementation independent code.
Posted Date:- 2021-08-21 08:52:33
When we use Collection API sorting algorithms to sort a collection, itâ€™s called sorted list. For small collections, itâ€™s not much of an overhead but for larger collections it can lead to slow performance and OutOfMemory errors. Also the entity beans should implement Comparable or Comparator interface for it to work, read more at java object list sorting.
If we are using Hibernate framework to load collection data from database, we can use itâ€™s Criteria API to use â€œorder byâ€ clause to get ordered list. Below code snippet shows you how to get it.
List<Employee> empList = session.createCriteria(Employee.class)
Ordered list is better than sorted list because the actual sorting is done at database level, that is fast and doesnâ€™t cause memory issues.
Posted Date:- 2021-08-21 08:48:38
General hibernate flow involving RDBMS is as follows:
a. Load configuration file and create object of configuration class.
b. Using configuration object, create sessionFactory object.
c. From sessionFactory, get one session.
d. Create HQL query.
e. Execute HQL query and get the results. Results will be in the form of a list.
Posted Date:- 2021-08-21 08:47:05
Derived properties are those properties which are not mapped to any columns of a database table. Such properties are calculated at runtime by evaluation of any expressions.
Posted Date:- 2021-08-21 08:45:31
Following fetching strategies are available in hibernate:
1. Join Fetching
2. Batch Fetching
3. Select Fetching
4. Sub-select Fetching
Posted Date:- 2021-08-21 08:45:05
Object identification can be done in hibernate in following three ways:
a. Using Object Identity: Using == operator.
b. Using Object Equality: Using equals() method.
c. Using database identity: Relational database objects can be identified if they represent same row.
Posted Date:- 2021-08-21 08:44:33
Hibernate session factory can be bound to JNDI by making configuration changes in hibernate.cfg file.
Posted Date:- 2021-08-21 08:43:53
Hibernate merge can be used to update existing values, however this method create a copy from the passed entity object and return it. The returned object is part of persistent context and tracked for any changes, passed object is not tracked.
Posted Date:- 2021-08-21 08:42:59
An entity bean instance can exist is one of the three states.
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. Detached instances may be made persistent by calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient or detached instance may also be made persistent as a new persistent instance by calling merge().
Posted Date:- 2021-08-21 08:42:20
Optimizing the performance of Hibernate applications is known as Hibernate tuning.
The performance tuning strategies for Hibernate are:
1. SQL Optimization
2. Session Management
3. Data Caching
Posted Date:- 2021-08-21 08:40:59
The means that the syntax is hidden from the business logic using specific design patterns. This is one of the valuable levels of ORM quality and this Light Object Mapping approach can be successful in case of applications where there are very fewer entities, or for applications having data models that are metadata-driven.
Posted Date:- 2021-08-21 08:39:53
Hibernate incorporates Dirty Checking feature that permits developers and users to avoid time-consuming write actions. This Dirty Checking feature changes or updates fields that need to be changed or updated, while keeping the remaining fields untouched and unchanged.
Posted Date:- 2021-08-21 08:38:50
Following are the four ORM levels in hibernate:
a. Pure Relational
b. Light Object Mapping
c. Medium Object Mapping
d. Full Object Mapping
Posted Date:- 2021-08-21 08:20:55
Hibernate provides dirty checking feature which can be used to reduce database write times. Dirty checking feature of hibernate updates only those fields which require a change while keeps others unchanged.
Posted Date:- 2021-08-21 08:19:41
Internal state of SessionFactory is immutable, so itâ€™s thread safe. Multiple threads can access it simultaneously to get Session instances.
Posted Date:- 2021-08-21 08:16:14
It is basically a technique that maps the object that is stored in the database. An ORM tool helps in simplifying data creation, manipulation, and access. It internally uses the Java API to interact with the databases.
Posted Date:- 2021-08-21 08:12:05
The configuration provides 2 key components, namely:
1. Database Connection: This is handled by one or more configuration files.
2. Class Mapping setup: It helps in creating the connection between Java classes and database tables.
Posted Date:- 2021-08-21 08:10:08
1. Hibernate is an ORM tool.
2. Hibernate uses Hibernate Query Language(HQL) which makes it database-independent.
3. It supports auto DDL operations.
4. This Java framework also has an Auto Primary Key Generation support.
4. Supports cache memory.
5. Exception handling is not mandatory in the case of Hibernate.
Posted Date:- 2021-08-21 08:07:48
1. Database Connection
2. Class Mapping Setup
Posted Date:- 2021-08-21 08:04:48
Some of the databases supported by Hibernate are:
4.Sybase SQL Server
5.Informix Dynamic Server
Posted Date:- 2021-08-21 08:01:19
ORM has the following advantages over JDBC:
1. Application development is fast.
2. Management of transaction.
3.Generates key automatically.
4. Details of SQL queries are hidden.
Posted Date:- 2021-08-21 07:59:37
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:
A. Transactional: This is used in cases of updating data that most likely causes stale data and this prevention is most critical to the application.
B. Read-Only: This is used when we don't want the data to be modified and can be used for reference data only.
C. Read-Write: Here, data is mostly read and is used when the prevention of stale data is of critical importance.
D. Non-strict-Read-Write: Using this strategy will ensure that there wouldn't be any consistency between the database and cache. This strategy can be used when the data can be modified and stale data is not of critical concern.
Posted Date:- 2021-08-21 07:56:08
Some of the strategies followed for solving the N+1 SELECT problem are:
1. Pre-fetch the records in batches which helps us to reduce the problem of N+1 to (N/K) + 1 where K refers to the size of the batch.
2. Subselect the fetching strategy
3. As last resort, try to avoid or disable lazy loading altogether.
Posted Date:- 2021-08-21 07:53:31
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.
Posted Date:- 2021-08-21 07:52:21
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.
Posted Date:- 2021-08-21 07:49:50
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.
Posted Date:- 2021-08-21 07:48:58
SQL injection attack is a serious vulnerability in terms of web security wherein an attacker can interfere with the queries made by an application/website to its database thereby allowing the attacker to view sensitive data which are generally irretrievable. It can also give the attacker to modify/ remove the data resulting in damages to the application behavior.
Hibernate does not provide immunity to SQL Injection. However, following good practices avoids SQL injection attacks. It is always advisable to follow any of the below options:
1.Incorporate Prepared Statements that use Parameterized Queries.
2.Use Stored Procedures.
3.Ensure data sanity by doing input validation.
Posted Date:- 2021-08-21 07:46:25