Professional Documents
Culture Documents
Most Hibernate-related application code primarily interacts with four interfaces provided by
Hibernate Core:
org.hibernate.Session
org.hibernate.SessionFactory
org.hibernate.Criteria
org.hibernate.Query
The Session is a persistence manager that manages operation like storing and retrieving objects.
Instances of Session are inexpensive to create and destroy. They are not thread safe.
The application obtains Session instances from a SessionFactory. SessionFactory instances are not
lightweight and typically one instance is created for the whole application. If the application
accesses multiple databases, it needs one per database.
The Criteria provides a provision for conditional search over the resultset.One can retrieve entities
by composing Criterion objects. The Session is a factory for Criteria.Criterion instances are usually
obtained via the factory methods on Restrictions.
Query represents object oriented representation of a Hibernate query. A Query instance is obtained
by calling Session.createQuery().
What is dirty checking in Hibernate?
Hibernate automatically detects object state changes in order to synchronize the updated state with
the database, this is called dirty checking. An important note here is, Hibernate will compare
objects by value, except for Collections, which are compared by identity. For this reason you should
return exactly the same collection instance as Hibernate passed to the setter method to prevent
unnecessary database updates.
What are different fetch strategies Hibernate have?
A fetching strategy in Hibernate is used for retrieving associated objects if the application needs to
navigate the association. They may be declared in the O/R mapping metadata, or over-ridden by a
particular HQL or Criteria query.
Hibernate3 defines the following fetching strategies:
Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT, using
an OUTER JOIN.
Select fetching - a second SELECT is used to retrieve the associated entity or collection. Unless
you explicitly disable lazy fetching by specifying lazy="false", this second select will only be
executed when you actually access the association.
Subselect fetching - a second SELECT is used to retrieve the associated collections for all entities
retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by specifying
lazy="false", this second select will only be executed when you actually access the association.
Batch fetching - an optimization strategy for select fetching - Hibernate retrieves a batch of entity
instances or collections in a single SELECT, by specifying a list of primary keys or foreign keys.
Hibernate also distinguishes between:
Immediate fetching - an association, collection or attribute is fetched immediately, when the owner
is loaded.
Lazy collection fetching - a collection is fetched when the application invokes an operation upon
that collection. (This is the default for collections.)
"Extra-lazy" collection fetching - individual elements of the collection are accessed from the
database as needed. Hibernate tries not to fetch the whole collection into memory unless absolutely
needed (suitable for very large collections)
Proxy fetching - a single-valued association is fetched when a method other than the identifier
getter is invoked upon the associated object.
"No-proxy" fetching - a single-valued association is fetched when the instance variable is accessed.
Compared to proxy fetching, this approach is less lazy (the association is fetched even when only
the identifier is accessed) but more transparent, since no proxy is visible to the application. This
approach requires buildtime bytecode instrumentation and is rarely necessary.
Lazy attribute fetching - an attribute or single valued association is fetched when the instance
variable is accessed. This approach requires buildtime bytecode instrumentation and is rarely
necessary.
We use fetch to tune performance. We may use lazy to define a contract for what data is always
available in any detached instance of a particular class.
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.
session.createQuery("select
count(*)
s.createFilter(
collection,
or:
from User user where exists elements(user.messages)
"select
Because of the inner join, this form can't be used to return a User with zero messages, so the
following form is also useful
select user
from User as user
left join user.messages as msg
group by user
having count(msg) = 0
select box
from Box box
left join box.balls ball
where ball is null
you could use this collection mapping (inside the mapping for class Foo):
You may also use an with a surrogate key column for the collection table. This would allow you to
have nullable columns.
An alternative approach is to simply map the association table as a normal entity class with two
bidirectional one-to-many associations.
in
query
and
data persisted to a
String
CHAR
SELECT
Follow the best practices guide! Ensure that all and mappings specify lazy="true" in Hibernate2
(this is the new default in Hibernate3). Use HQL LEFT JOIN FETCH to specify which associations
you need to be retrieved in the initial SQL SELECT.
A second way to avoid the n+1 selects problem is to use fetch="subselect" in Hibernate3.
If you are still unsure, refer to the Hibernate documentation and Hibernate in Action.
xmltype()
Specify custom SQL INSERT(and UPDATE) statements using and in Hibernate3, or using a custom
persister in Hibernate 2.1.
You will also need to write a UserTypeto perform binding to/from the PreparedStatement.
Or, in Hibernate3, override generated SQL using , , and in the mapping document.
I want to call an SQL function from HQL, but the HQL parser
does not recognize it!
Subclass your Dialect, and call registerFunction() from the constructor.
Answer:Use multiple elements. But, the recommended practice is to use one mapping file per
persistent class.
Question: How are the individual properties mapped to different table columns?
Answer: By using multiple elements inside the element.
Question: What are derived properties?
Answer: The properties that are not mapped to a column, but calculated at runtime by evaluation of
an expression are called derived properties. The expression can be defined using the formula
attribute of the element.
Question: How can you make a property be read from the database but not modified in anyway
(make it immutable)?
Answer: Use insert="false" and update="false" attributes.
Question: How can a whole class be mapped as immutable?
Answer: By using the mutable="false" attribute in the class mapping.
1.What is ORM ?
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 does ORM consists of ?
An ORM solution consists of the followig four pieces:
* API for performing basic CRUD operations
* API to express ries refering to classes
* Facilities to specify metadata
* Optimization facilities : dirty checking,lazy associations fetching
3.What are the ORM levels ?
The ORM levels are:
* Pure relational (stored procedure.)
* Light objects mapping (JDBC)
* Medium object mapping
* Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)
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.
5.Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart
from this, ORM provides following benefits:
* 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
6.What Does Hibernate Simplify?
Hibernate simplifies:
* Saving and retrieving your domain objects
* Making database column and table name changes
* Centralizing pre save and post retrieve logic
* Complex joins for retrieving related items
* Schema creation from object model
7.What is the need for Hibernate xml mapping file?
Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects.
Typical mapping file look as follows:
Programmatic configuration
The Session interface is the primary interface used by Hibernate applications. It is a singlethreaded, 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();
Session interface role:
* Wraps a JDBC connection
* Factory for Transaction
* Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph
or looking up objects by identifier
12.What role does the SessionFactory interface play in Hibernate?
The application obtains Session instances from a SessionFactory. There is typically a single
SessionFactory for the whole applicationcreated 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
SessionFactory sessionFactory = configuration.buildSessionFactory();
13.What is the general flow of Hibernate communication with RDBMS?
The general flow of Hibernate communication with RDBMS is :
* 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
14.What is Hibernate Query Language (HQL)?
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.
15.How do you map Java Objects with Database tables?
* First we need to write Java domain objects (beans with setter and getter). The variables should be
same as database columns.
* Write hbm.xml, where we map java class to table and database columns to Java class variables.
Example :
name="userName" not-null="true" type="java.lang.String"/>
name="userPassword" not-null="true" type="java.lang.String"/>
16.Whats the difference between load() and get()?
load() vs. get() :load()
get()
Only use the load() method if you are sure that the If you are not sure that the object exists,
then use one of the get() methods.
object exists.
method will throw an exception if the get() method will return null if the unique
unique id is not found in the database.
id is not found in the database.
load()
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a
parent who has a collection of children, should you ask the parent for its list of children, or ask the
children who the parents are?
20.What does it mean to be inverse?
It informs hibernate to ignore that end of the relationship. If the onetomany was marked as
inverse, hibernate would create a child>parent relationship (child.getParent). If the onetomany
was marked as noninverse then a child>parent relationship would be created.
23.Explain Criteria API
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very
convenient approach for functionality like "search" screens where there is a variable number of
conditions to be placed upon the result set.
Example :
List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();
24.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplateis
HibernateTemplate,
Session.
Example:
30.What is the difference between sorted and ordered collection in hibernate? sorted collection vs.
order collection :sorted collection
order collection
Hibernate
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a
parent who has a collection of children, should you ask the parent for its list of children, or ask the
children who the parents are?
35.What is Hibernate proxy?
The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will
initially return CGLIB proxies which implement the named interface. The actual persistent object
will be loaded when a method of the proxy is invoked.
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.
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.
38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very
convenient approach for functionality like "search" screens where there is a variable number of
conditions to be placed upon the result set.
* dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime
and contain only those columns whose values have changed
* dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and
contain only the columns whose values are not null.
39.What do you mean by fetching strategy ?
A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the
application needs to navigate the association. Fetch strategies may be declared in the O/R mapping
metadata, or over-ridden by a particular HQL or Criteria query.
40.What is automatic dirty checking?
Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to
update the database when we modify the state of an object inside a transaction.
41.What is transactional write-behind?
Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database
foreign key constraint violations but is still sufficiently predictable to the user. This feature is called
transactional write-behind.
People who read this also read:
JSP Interview Questions
Tibco Questions
webMethods Certification
Hibernate Interview Questions
XML Questions
42.What are Callback interfaces?
Callback interfaces allow the application to receive a notification when something interesting
happens to an objectfor example, when an object is loaded, saved, or deleted. Hibernate
applications don't need to implement these callbacks, but they're useful for implementing certain
kinds of generic functionality.
43.What are the types of Hibernate instance states ?
Three types of instance states:
* Transient -The instance is not associated with any persistence context
* Persistent -The instance is associated with a persistence context
* Detached -The instance was associated with a persistence context which has been closed
currently not associated
44.What are the differences between EJB 3.0 & Hibernate
Hibernate Vs EJB 3.0 :Hibernate
EJB 3.0
XDoclet Annotations used to support Attribute Java 5.0 Annotations used to support
Oriented Programming
Attribute Oriented Programming
Defines HQL for expressing queries to the
Defines EJB QL for expressing queries
database
Supports Entity Relationships through Support Entity Relationships through Java
mapping files and annotations in JavaDoc
5.0 annotations
Provides a Persistence Manager API exposed
Provides and Entity Manager Interface for
via the Session, Query, Criteria, and Transaction
managing CRUD operations for an Entity
API
Provides callback support through lifecycle, Provides callback support through Entity
interceptor, and validatable interfaces
Listener and Callback methods
Entity Relationships are unidirectional.
Entity Relationships are bidirectional or
Bidirectional relationships are implemented by
unidirectional
two unidirectional relationships
45.What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
no need to care about table structures. This works very well for stored procedures, works very well
for reporting applications, etc,.
Now the question is , does it work well for simple CRUD applications? Well, it works because what
we have to write is sql. Then why not use Hibernate for that?
You can start see Some of the decision criteria that comes into play. So one of the other follow on
questions that typically get is , can I use both? Thats really interesting question! because the
answer is sure.
But,such a thing will never ever exists is java persistence world. However we can kind of use both
to create this little hybrid. So think of this kind scenario, we have very large application where
Hibernate is working very well for it, but we have a reporting piece that just is a real nag , its query
only , so we can do is, we can use iBatis to pull up the queries for reporting piece and still use
Hibernate for all the operational stuff and updates. This model actually works well, it doesnt break
the transactional model, and it doesnt affect any of the primary & secondary caches with a
Hibernate. Its a good solution.
* Use iBatis if
o You want to create your own SQL's and are willing to maintain them
o your environment is driven by relational data model
o you have to work existing and complex schema's
* Use Hibernate if
o your environment is driven by object model and wants generates SQL automatically
The message is,
* One size does not fit all the java persistence and the important to know there are other solutions
besides the traditional ORMs, and that would be iBatis.
* Both the solutions work well, given their specific domain.
* Look for the opportunity where you can use both.
What is iBatis ?
* A JDBC Framework
o Developers write SQL, iBATIS executes it using JDBC.
o No more try/catch/finally/try/catch.
* An SQL Mapper
o Automatically maps object properties to prepared statement parameters.
o Automatically maps result sets to objects.
o Support for getting rid of N+1 queries.
* A Transaction Manager
o iBATIS will provide transaction management for database operations if no other transaction
manager is available.
o iBATIS will use external transaction management (Spring, EJB CMT, etc.) if available.
* Great integration with Spring, but can also be used without Spring (the Spring folks were early
supporters of iBATIS).
What isnt iBATIS ?
* An ORM
o Does not generate SQL
o Does not have a proprietary query language
o Does not know about object identity
o Does not transparently persist objects
o Does not build an object cache
Essentially, iBatis is a very lightweight persistence solution that gives you most of the semantics of
an O/R Mapping toolkit, without all the drama. In other words ,iBATIS strives to ease the
development of data-driven applications by abstracting the low-level details involved in database
communication (loading a database driver, obtaining and managing connections, managing
transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and
configurable mapping of objects to SQL calls, data type conversion management, support for static
queries as well as dynamic queries based upon an object's state, mapping of complex joins to
complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very
simple XML descriptor. Simplicity is the key advantage of iBATIS over other frameworks and
object relational mapping tools.
Simply Singleton
Navigate the deceptively simple Singleton pattern
By David Geary, JavaWorld.com, 04/25/03
Sometimes it's appropriate to have exactly one instance of a class: window managers, print
spoolers, and filesystems are prototypical examples. Typically, those types of objectsknown as
singletonsare accessed by disparate objects throughout a software system, and therefore require a
global point of access. Of course, just when you're certain you will never need more than one
instance, it's a good bet you'll change your mind.
The Singleton design pattern addresses all of the previous paragraph's concerns. With the Singleton
design pattern you can:
Allow multiple instances in the future without affecting a singleton class's clients
Although the Singleton design patternas evidenced below by the figure belowis one of the
simplest design patterns, it presents a number of pitfalls for the unwary Java developer. This article
discusses the Singleton design pattern and addresses those pitfalls.
Note: You can download this article's source code from Resources.
How can the class in the preceding code fragmentwhich does not extend ClassicSingleton
create a ClassicSingleton instance if the ClassicSingleton constructor is protected? The
answer is that protected constructors can be called by subclasses and by other classes in the same
package. Because ClassicSingleton and SingletonInstantiator are in the same package (the
default package), SingletonInstantiator()methods can create ClassicSingletoninstances.
This dilemma has two solutions: You can make the ClassicSingleton constructor private so that
only ClassicSingleton()methods call it; however, that means ClassicSingletoncannot be
subclassed. Sometimes, that is a desirable solution; if so, it's a good idea to declare your singleton
class final, which makes that intention explicit and allows the compiler to apply performance
optimizations. The other solution is to put your singleton class in an explicit package, so classes in
other packages (including the default package) cannot instantiate singleton instances.
A third interesting point about ClassicSingleton: it's possible to have multiple singleton instances
if classes loaded by different classloaders access a singleton. That scenario is not so far-fetched; for
example, some servlet containers use distinct classloaders for each servlet, so if two servlets access
a singleton, they will each have their own instance.
Fourth, if ClassicSingletonimplements the java.io.Serializableinterface, the class's
instances can be serialized and deserialized. However, if you serialize a singleton object and
subsequently deserialize that object more than once, you will have multiple singleton instances.
Finally, and perhaps most important, Example 1's ClassicSingleton class is not thread-safe. If
two threadswe'll call them Thread 1 and Thread 2call ClassicSingleton.getInstance() at
the same time, two ClassicSingletoninstances can be created if Thread 1 is preempted just after
it enters the if block and control is subsequently given to Thread 2.
As you can see from the preceding discussion, although the Singleton pattern is one of the simplest
design patterns, implementing it in Java is anything but simple. The rest of this article addresses
Java-specific considerations for the Singleton pattern, but first let's take a short detour to see how
you can test your singleton classes.
strings are routinely concatenated. Using the String class, concatenations are typically performed
as follows:
String str = new String ("Stanford ");
str += "Lost!!";
you were to use StringBufferto perform the same
If
looks like this:
Developers usually assume that the first example above is more efficient because they think that the
second example, which uses the append method for concatenation, is more costly than the first
example, which uses the + operator to concatenate two String objects.
The + operator appears innocent, but the code generated produces some surprises. Using a
StringBuffer for concatenation can in fact produce code that is significantly faster than using a
String. To discover why this is the case, we must examine the generated bytecode from our two
examples. The bytecode for the example using Stringlooks like this:
0 new #7
3 dup
4 ldc #2
6 invokespecial #12
9 astore_1
10 new #8
13 dup
14 aload_1
15 invokestatic #23
18 invokespecial #13
21 ldc #1
23 invokevirtual #15
26 invokevirtual #22
29 astore_1
The bytecode at locations 0 through 9 is executed for the first line of code, namely:
String str = new String("Stanford ");
Things get interesting here. The bytecode generated for the concatenation creates a
StringBufferobject, then invokes its appendmethod: the temporary StringBufferobject is
created at location 10, and its appendmethod is called at location 23. Because the Stringclass is
immutable, a StringBuffermust be used for concatenation.
After the concatenation is performed on the StringBuffer object, it must be converted back into a
String. This is done with the call to the toString method at location 26. This method creates a
new Stringobject from the temporary StringBufferobject. The creation of this temporary
StringBufferobject and its subsequent conversion back into a String object are very expensive.
In summary, the two lines of code above result in the creation of three objects:
1. A String object at location 0
2. A StringBuffer object at location 10
3. A String object at location 26
Now, let's look at the bytecode generated for the example using StringBuffer:
0 new #8
3 dup
4 ldc #2
6 invokespecial #13
9 astore_1
10 aload_1
11 ldc #1
13 invokevirtual #15
16 pop
Notice that, as is the case in the first example, this code invokes the append method of a
StringBuffer object. Unlike the first example, however, there is no need to create a temporary
StringBuffer and then convert it into a String object. This code creates only one object, the
StringBuffer, at location 0.
In conclusion, StringBufferconcatenation is significantly faster than Stringconcatenation.
Obviously, StringBuffers should be used in this type of operation when possible. If the
functionality of the String class is desired, consider using a StringBufferfor concatenation and
then performing one conversion to String.
The other strength of the PreparedStatementis that you can use it over and over again with new
parameter values, rather than having to create a new Statementobject for each new set of
parameters. This approach is obviously more efficient, as only one object is created.
Use the set methods each time to specify new parameter values.
Q. What is a Session? Can you share a session object between different theads?
A. 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.
?
1
2
3 public class HibernateUtil {
public static final ThreadLocal local = new ThreadLocal();
4
public static Session currentSession() throws HibernateException {
5
Session session = (Session) local.get();
6
//open a new session if this thread has no session
if(session == null) {
7
session = sessionFactory.openSession();
8
local.set(session);
9
}
10
return session;
11
}
12 }
13
14
It is also vital that you close your session after your unit of work completes. Note: Keep your
Hibernate Session API handy. Quite often, hibernate is used with Spring framework, using the
HibernateTemplate.
Q. Explain hibernate object states? Explain hibernate objects life cycle?
A.
Persistent objects and collections are short lived single threaded objects, which store the persistent
state. These objects synchronize their state with the database depending on your flush strategy (i.e.
auto-flush where as soon as setXXX() method is called or an item is removed from a Set, List etc
or define your own synchronization points with session.flush(), transaction.commit() calls). If you
remove an item from a persistent collection like a Set, it will be removed from the database either
immediately or when flush() or commit() is called depending on your flush strategy. They are Plain
Old Java Objects (POJOs) and are currently associated with a session. As soon as the associated
session is closed, persistent objects become detached objects and are free to use directly as data
transfer objects in any application layers like business layer, presentation layer etc.
Detached objects and collections are instances of persistent objects that were associated with a
session but currently not associated with a session. These objects can be freely used as Data
Transfer Objects without having any impact on your database. Detached objects can be later on
attached to another session by calling methods like session.update(), session.saveOrUpdate() etc.
and become persistent objects.
Transient objects and collections are instances of persistent objects that were never associated with
a session. These objects can be freely used as Data Transfer Objects without having any impact on
your database. Transient objects become persistent objects when associated to a session by calling
methods like session.save( ), session.persist( ) etc.
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 it is better not to 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.
//myCar is a persistent
//once the session is closed
you can now pass the myCar object all the way upto the presentation tier. It can be modified
without any effect to your database table.
?
1 myCar.setColor(Red);
When you are ready to persist this change to the database, it can be reattached to another session as
shown below:
?
1Session session2 = sessionFactory.openSession();
2Transaction tx = session2.beginTransaction();
//detached object myCar gets re-attached
3session2.update(myCar);
tx.commit();
//change is synchronized with the database.
4
session2.close()
5
Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached
objects?
A.
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.
Note: When you reattach detached objects, you need to make sure that the dependent objects are
reattached as well.
You can access (and modify) the Hibernate metamodel via the Configuration object, using
getClassMapping(), getCollectionMapping(), etc.
Note that the SessionFactory is immutable and does not retain any reference to the Configuration
instance, so you must re-build it if you wish to activate the modified mappings.
25. How can I avoid n+1 SQL SELECT queries when running a Hibernate query?
Follow the best practices guide! Ensure that all and mappings specify lazy="true" in Hibernate2
(this is the new default in Hibernate3). Use HQL LEFT JOIN FETCH to specify which associations
you need to be retrieved in the initial SQL SELECT.
A second way to avoid the n+1 selects problem is to use fetch="subselect" in Hibernate3.
If you are still unsure, refer to the Hibernate documentation and Hibernate in Action.
I have a collection with second-level cache enabled, and Hibernate retrieves the collection elements
one at a time with a SQL query per element!
Enable second-level cache for the associated entity class. Don't cache collections of uncached entity
types.
26. How can I insert XML data into Oracle using the xmltype() function?
Specify custom SQL INSERT (and UPDATE) statements using and in Hibernate3, or using a
custom persister in Hibernate 2.1.
You will also need to write a UserType to perform binding to/from the PreparedStatement.
27. How can I execute arbitrary SQL using Hibernate?
PreparedStatement ps = session.connection().prepareStatement(sqlString);
Or, if you wish to retrieve managed entity objects, use session.createSQLQuery().
Or, in Hibernate3, override generated SQL using , , and in the mapping document.
I want to call an SQL function from HQL, but the HQL parser does not recognize it!
Subclass your Dialect, and call registerFunction() from the constructor.
28. Why to use HQL?
Full support for relational operations: HQL allows representing SQL queries in the form of
objects. Hibernate Query Language uses Classes and properties instead of tables and columns.
Return result as Object: The HQL queries return the query result(s) in the form of object(s), which
is easy to use. This eliminates the need of creating the object and populate the data from result set.
Polymorphic Queries: HQL fully supports polymorphic queries. Polymorphic queries results the
query results along with all the child objects if any.
Easy to Learn: Hibernate Queries are easy to learn and it can be easily implemented in the
applications.
Support for Advance features: HQL contains many advance features such as pagination, fetch join
with dynamic profiling, Inner/outer/full joins, Cartesian products. It also supports Projection,
Aggregation (max, avg) and grouping, Ordering, Sub queries and SQL function calls.
Database independent: Queries written in HQL are database independent (If database supports the
underlying feature).
1.What is ORM ?
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 does ORM consists of ?
An ORM solution consists of the followig four pieces:
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.
5.Why do you need ORM tools like hibernate?
The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart
from this, ORM provides following benefits:
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
Programmatic configuration
Session interface
SessionFactory interface
Configuration interface
Transaction interface
Holds a mandatory (first-level) cache of persistent objects, used when navigating the object
graph or looking up objects by identifier
Load the Hibernate configuration file and create configuration object. It will automatically
load all hbm mapping files
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"
</class>
</hibernate-mapping>
type="java.lang.String"/>