What Is ORM ?: Improved Productivity
What Is ORM ?: Improved Productivity
What Is ORM ?: Improved Productivity
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java
application to the tables in a relational database.
4. What is Hibernate?
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.
Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
Improved maintainability
o A lot less code to write
Improved portability
o ORM framework generates database-specific SQL for you
1
Hibernate
Schema creation from object model
Programmatic configuration
XML configuration (hibernate.cfg.xml)
2
Hibernate
10. What are the Core interfaces are of Hibernate framework?
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.
Session interface
SessionFactory interface
Configuration interface
Transaction interface
Query and Criteria interfaces
3
Hibernate
The application obtains Session instances from a SessionFactory. There is typically a
single SessionFactory for the whole application—created during application
initialization. The SessionFactory caches generate SQL statements and other mapping
metadata that Hibernate uses at runtime. It also holds cached data that has been read
in one unit of work and may be reused in a future unit of work
Load the Hibernate configuration file and create configuration object. It will
automatically load all hbm mapping files
Create session factory from configuration object
Get one session from this session factory
Create HQL Query
Execute query to get list containing Java objects
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.
Example :
<hibernate-mapping>
<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"/>
</class>
</hibernate-mapping>
load() get()
4
Hibernate
If you are not sure that the object
Only use the load() method if you are sure
exists, then use one of the get()
that the object exists.
methods.
load() method will throw an exception if the get() method will return null if the
unique id is not found in the database. unique id is not found in the database.
5
Hibernate
FROM Employee EMP WHERE emp.NAME LIKE :name
</sql-query>
23.Define HibernateTemplate?
6
Hibernate
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides
different methods for querying/retrieving data from the database. It also converts checked
HibernateExceptions into unchecked DataAccessExceptions.
7
Hibernate
If your collection is not large, it will be If your collection is very large, it will be
more efficient way to sort it. more efficient way to sort it .
31.What is the advantage of Hibernate over jdbc?
Hibernate Vs. JDBC :-
JDBC Hibernate
With JDBC, developer has to write code to Hibernate is flexible and powerful ORM
map an object model's data representation solution to map Java classes to database
to a relational data model and its tables. Hibernate itself takes care of this
corresponding database schema. mapping using XML files so developer does
8
Hibernate
not need to write code for this.
In JDBC there is no check that always every Hibernate enables developer to define
user has updated data. This check has to be version type field to application, due to
added by the developer. this defined field Hibernate updates version
9
Hibernate
field of database table every time
relational tuple is updated in form of Java
class object to that table. So if two users
retrieve same tuple and then modify it and
one user save this modified tuple to
database, version is automatically updated
for this tuple by Hibernate. When other
user tries to save updated tuple to
database then it does not allow saving it
because this user does not have updated
data.
32.What are the Collection types in Hibernate ?
Bag
Set
List
Array
Map
36.How can Hibernate be configured to access an instance variable directly and not
through a setter method ?
By mapping the property with access="field" in Hibernate metadata. This forces hibernate to
bypass the setter method and access the instance variable directly while initializing a newly
loaded object.
10
Hibernate
37.How can a whole class be mapped as immutable?
Mark the class as mutable="false" (Default is true),. This specifies that instances of the class
are (not) mutable. Immutable classes, may not be updated or deleted by the application.
Answer:
The configuration files hibernate.cfg.xml (or hibernate.properties) and mapping files
*.hbm.xml are used by the Configuration class to create (i.e. configure and bootstrap
hibernate) the SessionFactory, which in turn creates the Session instances. Session instances
are the primary interface for the persistence service.
" hibernate.cfg.xml (alternatively can use hibernate.properties): These two files are used to
configure the hibernate sevice (connection driver class, connection URL, connection
username, connection password, dialect etc). If both files are present in the classpath then
11
Hibernate
hibernate.cfg.xml file overrides the settings found in the hibernate.properties file.
" Mapping files (*.hbm.xml): These files are used to map persistent objects to a relational
database. It is the best practice to store each object in an individual mapping file (i.e
mapping file per class) because storing large number of persistent classes into one mapping
file can be difficult to manage and maintain. The naming convention is to use the same name
as the persistent (POJO) class name. For example Account.class will have a mapping file
named Account.hbm.xml. Alternatively hibernate annotations can be used as part of your
persistent class code instead of the *.hbm.xml files.
Answer:
SessionFactory is Hibernates concept of a single datastore and is threadsafe so that many
threads can access it concurrently and request for sessions and immutable cache of compiled
mappings for a single database. A SessionFactory is usually only built once at startup.
SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed
in an application code.
Q. What is a Session? Can you share a session object between different theads?
Answer:
Session is a light weight and a non-threadsafe object (No, you cannot share it between
threads) that represents a single unit-of-work with the database. Sessions are opened by a
SessionFactory and then are closed when all work is complete. Session is the primary
interface for the persistence service. A session obtains a database connection lazily (i.e. only
when required). To avoid creating too many sessions ThreadLocal class can be used as shown
below to get the current session no matter how many times you make call to the
currentSession() method.
&
public class HibernateUtil {
&
public static final ThreadLocal local = new ThreadLocal();
12
Hibernate
local.set(session);
}
return session;
}
}
It is also vital that you close your session after your unit of work completes. Note: Keep your
Hibernate Session API handy.
Answer:
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.
Answer:
Pros:
" When long transactions are required due to user think-time, it is the best practice to break
the long transaction up into two or more transactions. You can use detached objects from the
first transaction to carry data all the way up to the presentation layer. These detached
objects get modified outside a transaction and later on re-attached to a new transaction via
another session.
Cons
" In general, working with detached objects is quite cumbersome, and better to not clutter up
the session with them if possible. It is better to discard them and re-fetch them on
subsequent requests. This approach is not only more portable but also more efficient because
- the objects hang around in Hibernate's cache anyway.
" Also from pure rich domain driven design perspective it is recommended to use DTOs
(DataTransferObjects) and DOs (DomainObjects) to maintain the separation between Service
and UI tiers.
Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and
detached objects?
13
Hibernate
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().
1. What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service.This
lets the users to develop persistent classes following object-oriented principles such as
association, inheritance, polymorphism, composition, and collections.
2. What is ORM?
ORM stands for Object/Relational mapping. It is the programmed and translucent
14
Hibernate
perseverance of objects in a Java application in to the tables of a relational database using the
metadata that describes the mapping between the objects and the database. It works by
transforming the data from one representation to another.
15
Hibernate
one. i. Productivity – Hibernate reduces the burden of developer by providing much of
the functionality and let the developer to concentrate on business logic.
ii. Maintainability – As hibernate provides most of the functionality, the LOC for the
application will be reduced and it is easy to maintain. By automated object/relational
persistence it even reduces the LOC.
iii. Performance – Hand-coded persistence provided greater performance than
automated one. But this is not true all the times. But in hibernate, it provides more
optimization that works all the time there by increasing the performance. If it is
automated persistence then it still increases the performance.
iv. Vendor independence – Irrespective of the different types of databases that are
there, hibernate provides a much easier way to develop a cross platform application.
11. What is a hibernate xml mapping document and how does it look like?
In order to make most of the things work in hibernate, usually the information is provided in an
xml document. This document is called as xml mapping document. The document defines,
among other things, how properties of the user defined persistence classes’ map to the columns
of the relative tables in database.
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
<hibernate-mapping>
<class name="sample.MyPersistanceClass" table="MyPersitaceTable">
<id name="id" column="MyPerId">
<generator class="increment"/>
</id>
<property name="text" column="Persistance_message"/>
<many-to-one name="nxtPer" cascade="all" column="NxtPerId"/>
</class>
</hibernate-mapping>
Everything should be included under <hibernate-mapping> tag. This is the main tag for
an xml mapping document.
16
Hibernate
13. What the Core interfaces are of hibernate framework?
There are many benefits from these. Out of which the following are the most important
one.
i. Session Interface – This is the primary interface used by hibernate applications.
The instances of this interface are lightweight and are inexpensive to create and destroy.
Hibernate sessions are not thread safe.
ii. SessionFactory Interface – This is a factory that delivers the session objects to
hibernate application. Generally there will be a single SessionFactory for the whole
application and it will be shared among all the application threads.
iii. Configuration Interface – This interface is used to configure and bootstrap
hibernate. The instance of this interface is used by the application in order to specify the
location of hibernate specific mapping documents.
iv. Transaction Interface – This is an optional interface but the above three interfaces
are mandatory in each and every application. This interface abstracts the code from any
kind of transaction implementations such as JDBC transaction, JTA transaction.
v. Query and Criteria Interface – This interface allows the user to perform queries
and also control the flow of the query execution.
16. What are the Extension interfaces that are there in hibernate?
There are many extension interfaces provided by hibernate.
ı ProxyFactory interface - used to create proxies
ı ConnectionProvider interface – used for JDBC connection management
ı TransactionFactory interface – Used for transaction management
ı Transaction interface – Used for transaction management
ı TransactionManagementLookup interface – Used in transaction management.
ı Cahce interface – provides caching techniques and strategies
ı CacheProvider interface – same as Cache interface
ı ClassPersister interface – provides ORM strategies
ı IdentifierGenerator interface – used for primary key generation
ı Dialect abstract class – provides SQL support
18. What is the file extension you use for hibernate mapping file?
The name of the file should be like this : filename.hbm.xml
The filename varies here. The extension of these files should be “.hbm.xml”.
This is just a convention and it’s not mandatory. But this is the best practice to follow this
extension.
18
Hibernate
Method chaining is a programming technique that is supported by many hibernate
interfaces. This is less readable when compared to actual java code. And it is not
mandatory to use this format. Look how a SessionFactory is created when we use method
chaining.
SessionFactory sessions = new Configuration()
.addResource("myinstance/MyConfig.hbm.xml")
.setProperties( System.getProperties() )
.buildSessionFactory();
26. What are the different types of property and class mappings?
• Typical and most common property mapping
<property name="description" column="DESCRIPTION" type="string"/>
19
Hibernate
Or
<property name="description" type="string">
<column name="DESCRIPTION"/>
</property>
• Derived properties
<property name="averageBidAmount" formula="( select AVG(b.AMOUNT) from BID b
where b.ITEM_ID = ITEM_ID )" type="big_decimal"/>
• Typical and most common property mapping
<property name="description" column="DESCRIPTION" type="string"/>
• Controlling inserts and updates
<property name="name" column="NAME" type="string"
insert="false" update="false"/>
20
Hibernate