0% found this document useful (0 votes)
62 views

Hibernate FAQ: 1. What Is ORM? A 2. What Is Hibernate? A

Hibernate is an object-relational mapping tool that allows developers to map Java objects to database tables. It automates the process of persisting objects to a relational database and allows developers to work with data at the object level rather than the database level. Some key benefits of Hibernate include improved productivity by reducing the amount of code needed, improved performance through features like caching and lazy/eager loading, and improved maintainability and portability.

Uploaded by

manjunathss235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views

Hibernate FAQ: 1. What Is ORM? A 2. What Is Hibernate? A

Hibernate is an object-relational mapping tool that allows developers to map Java objects to database tables. It automates the process of persisting objects to a relational database and allows developers to work with data at the object level rather than the database level. Some key benefits of Hibernate include improved productivity by reducing the amount of code needed, improved performance through features like caching and lazy/eager loading, and improved maintainability and portability.

Uploaded by

manjunathss235
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 7

Hibernate FAQ

1. What is ORM?
A ORM stands for object/relational mapping. ORM is the automated persistence of objects in a
Java application to the tables in a relational database.
2. What is Hibernate?
A Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that
allows you to map plain old Java objects to relational database tables using (XML) configuration
files. Its purpose is to relieve the developer from a significant amount of relational data
persistence-related programming tasks.
3. What is the advantage of using hibernate?
A Following are the advantages of using Hibernate
a) Improved productivity:
 High-level object-oriented API
 Less Java code to write
 No SQL to write
b) Improved performance:
 Sophisticated caching
 Lazy loading
 Eager loading
c) Improved maintainability
 A lot less code to write
d) Improved portability
 ORM framework generates database-specific SQL for you
4. What are the Core interfaces are of Hibernate framework?
A The five core interfaces are used in just about every Hibernate application. Using these
interfaces, you can store and retrieve persistent objects and control transactions.
a) Session interface
b) SessionFactory interface
c) Configuration interface
d) Transaction interface
e) Query and Criteria interfaces
5. Difference between get() and load() method?

get() load()
returns null if object is not found in cache as It throws ObjectNotFoundException if object is
well as on database not found on cache as well as on database but
never return null.
get method always hit database load() method may not always hit the database,
depending upon which method is called.
get method never returns a proxy, it either while load() method may return proxy.
returns null or fully initialized Object.

6. Difference between save() and saveOrUpdate()?

save() saveOrUpdate()
It generates a new identifier and INSERT record saveOrUpdate can either INSERT or UPDATE
into database based upon existence of record.
save is faster compared to saveOrUpadate saveOrUpdate is slower because it needs to do
an extra search operation to find out whether
key is already there in database.
save return Serializable object It returns void

7. Difference between save and persist method?

save() persist()
save return Serializable object persist returns void.
It guarantee that the identifier value will be persist() method doesn't guarantee that the
assigned to the persistent instance immediately identifier value will be assigned to the persistent
instance immediately, the assignment might
happen at flush time.
save() method does not guarantees that it will persist() method guarantees that it will not
not execute an INSERT statement if it is called execute an INSERT statement if it is called
outside of transaction boundaries outside of transaction boundaries

8. What is named SQL query in Hibernate?


A Named queries are SQL queries which are defined in mapping document using <sql-query> tag
and called using Session.getNamedQuery() method. Named query allows you to refer a
particular query by the name you provided, by the way you can define named query in
hibernate either by using annotations or xml mapping file, as I said above. @NameQuery is used
to define single named query and @NameQueries is used to define multiple named query in
hibernate.
9. What is SessionFactory in Hibernate? Is SessionFactory thread-safe?
 SessionFactory as name suggest is a factory to create hibernate Session objects.
 SessionFactory is often built during start-up and used by application code to get session object.
 It acts as single data store and it’s also thread-safe so that multiple threads can use same
SessionFactory.
 Usually a Java JEE application has just one SessionFactory, and individual threads, which are
servicing client’s request obtain hibernate Session instances from this factory, that’s why any
implementation of SessionFactory interface must be thread-safe.
 Also internal state of SessionFactory, which contains all Meta data about Object/Relational
mapping is Immutable and cannot be changed once created.
10. What is Session in Hibernate? Can we share single Session among multiple threads in Hibernate?
 Session represents a small unit of work in Hibernate, they maintain connection with database
and they are not thread-safe, it means you cannot share Hibernate Session between multiple
threads.
 Though Session obtains database connection lazily it's good to close session as soon as you are
done with it.
11. What is difference between sorted and ordered collection in hibernate?
 A sorted collection is sorted in memory by using Java Comparator, while an ordered collection
uses database's order by clause for ordering.
 For large data set it's better to use ordered collection to avoid any OutOfMemoryError in Java,
by trying to sort them in memory.
12. What is difference between transient, persistent and detached object in Hibernate?
 In Hibernate, Object can remain in three states transient, persistent or detached.
 An object which is associated with Hibernate session is called persistent object. Any change in
this object will reflect in database based upon your flush strategy i.e. automatic flush whenever
any property of object change or explicit flushing by calling session.flush() method.
 On the other hand if an object which is earlier associated with Session, but currently not
associated with it are called detached object. You can reattach detached object to any other
session by calling either update() or saveOrUpdate() method on that session.
 Transient objects are newly created instance of persistence class, which is never associated with
any Hibernate Session. Similarly you can call persist() or save() methods to make transient object
persistent. Just remember, here transient doesn’t represent transient keyword in Java, which is
altogether different thing.
13. How can you convert Transient instances to persistent instances?
 Transient instances may be made persistent by calling 
 save()
 persist()
 saveOrUpdate().
 Any instance returned by a get() or load() method is persistent
14. How can you convert persistent instances to Transient instances?
A Persistent instances may be made transient by calling delete() method.

15. How can you convert detached instances to persistent instances?


A Detached instances may be made persistent by calling 
 update()
 saveOrUpdate()
 lock() or replicate().

16. What are the benefits of detached objects?


A Detached objects can be passed across layers all the way up to the presentation layer without
having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects
to another session.
17. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects?
A Hibernate uses the version property, if there is one. If not uses the identifier value. No identifier
value means a new object. This does work only for Hibernate managed surrogate keys. Does not
work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. Write your
own strategy with Interceptor.isUnsaved().
18. How would you reattach detached objects to a session when the same object has already been
loaded into the session?
A You can use the session.merge() method call.
19. What are the general considerations or best practices for defining your Hibernate persistent classes?
 You must have a default no-argument constructor for your persistent classes and there should
be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persist
able instance variables.
 You should implement the equals() and hashCode() methods based on your business key and it
is important not to use the id field in your equals() and hashCode() definition if the id field is a
surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates
and sets the field when saving the object.
 It is recommended to implement the Serializable interface. This is potentially useful if you want
to migrate around a multi-processor cluster.
 The persistent class should not be final because if it is final then lazy loading cannot be used by
creating proxy objects.
 Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which
are less verbose than *.hbm.xml files.

20. What is Hibernate Query Language (HQL)?


A Hibernate offers a query language that embodies a very powerful and flexible mechanism to
query, store, update, and retrieve objects from a database. This language, the Hibernate query
Language (HQL), is an object-oriented extension to SQL.
21. What is Hibernate proxy?
A The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will
initially return proxies which implement the named interface. The actual persistent object will
be loaded when a method of the proxy is invoked.

22. What is use of “inverse=true”?


A It is used to specify the relationship owner. By default “inverse=false” which means parent is the
relationship owner. If “inverse=true” that means child will be relationship owner.
23. What is the use of “cascade” attribute?
A cascade is used to specify whether, after one operation (save, update and delete) is done, it
decide whether it need to call other operations (save, update and delete) on another entities
which has relationship with each other.

Q What are named queries in Hibernate?


A Named queries in Hibernate are HQL query technique to group the HQL statements in single
location. We can lately refer them by some name whenever need to use them. This technique
avoids scattering of HQL queries throughout the application
Following are steps to write named queries

Step 1: Define the HQL query. This can be either done in xml mapping file or with annotations
a. With XML configuration:
<query name="Employee.findByEname">
select e.empid, e.ename,e.email from Employee e where
e.ename = :nme
</query>
Note: <query> tag should be declared after </class> tag
b. With annotations configuration: annotate the entity with @NamedQuery() as follows

@Entity
@Table(name="employee")
@NamedQuery(name="Employee.findByEname", query="select e.empid,
e.ename,e.email from Employee e where e.ename = :nme")
public class Employee {

Note: If you want to declare multiple HQL queries at once then you can use
@NamedQueries which accepts array of @NamedQuery

Step 2: To get the named query use the getNamedQuery() of Session interface. And use
setString() or setInteger() to give named parameter as follows

Query q = ses.getNamedQuery("Employee.findByEname").setString("nme",
"JAMES");
Q Difference between SQL and HQL

SQL HQL
SQL is based on a relational database model HQL is a combination of object-oriented
programming with relational database concepts
SQL manipulates data stored in tables and HQL is concerned about objects and its properties
modifies its rows and columns
SQL is concerned about the relationship that exists HQL considers the relation between two objects
between two tables

Q When to use update() and merge() methods of Session interface ?


A update() should be used when you are sure that the session does not contains an already
persistent instance with the same identifier on that time we have to use update() to save the
data in hibernate
merge() should be used when you want to save your modifications at any time without knowing
about the state of the Session then use merge() in hibernate.

Q What are different possible values of fetch attributes are in hibernate?


 join: Hibernate retrieves the associated instance or collection in the single SELECT, using an
OUTER JOIN. It disables the lazy loading and always load all the collections and entities
 select: It executes multiple SELECT. It lazily loads all the collections and entities.
 subselect: It uses sub select statements to group its collection and entities.

(Note: batch-size="" is also considered as a fetch strategy which Fetches up to ‘N’ collections
or entities)

Q Which SQL operations are performed when we call different methods of Session interface?

SQL Operations methods of Session interface


INSERT save(), persist(), saveOrUpdate() and replicate().
UPDATE update(), merge(), saveOrUpdate() and replicate().
DELETE delete().
READ load(), get().

Note:- saveOrUpdate() and replicate() result in either an INSERT or an UPDATE.


Q When to use load()?
A
1. If your goal is largely transactional, and you are only going to be accessing the JavaBean of
interest within a single unit of work that will pretty much end once the transaction is
committed, you'll want to use the load method
2. If you want to ensure that the JavaBean of interest is completely in sync with the database
when it is used, you'll want to be using the load method as well, as this will ensure the fields
of the JavaBean are being loaded in from the database, and are not just being loaded from
the memory of the cache.
3. The load method may be the method of choice if you know, and are absolutely sure, that
the entity you are searching for exists in the database with the primary key you are
providing

Q When to use get()?


A
1. If you ever want to use the object that you are retrieving from the database after the
database transaction has been committed, you'll want to use the get method.
2. If you don't know for sure that an entity bearing your primary key exists in the database, you
can use the get method, and check to see if the instance that gets returned from the
method call returns null.

You might also like