What is Hibernate?
Hibernate is a powerful, high performance object/relational persistence and query service.It is an open-source technology which fits well both with Java and .NET technologies.Hibernate lets developers write persistence classes with hibernate query features of HQL within principles of Object Oriented paradigm.It means one can include association,inheritance,polymorphism,composition and collection of these persisting objects to build applications.
Hibernate Architecture
The main objective of Hibernate is to relieve the developers from manual handling of SQLs,JDBC APIs for resultsets handling and it helps in keeping your data portable to various SQL databases,just by switching the delegate and driver details in hibernate.cfg.xml file.
Hibernate offers sophisticated query options, you can write plain SQL, object-oriented HQL (Hibernate Query Language), or create programmatic criteria and example queries. Hibernate can optimize object loading all the time, with various fetching and caching options.
Some snapshots of Hibernate:
-Free open source
-OO Concepts can be implemented.
-A rich variety of mappings for collections and dependent objects
-No extra code generation or bytecode processing steps in your build procedure
-Great performance, has a dual-layer cache architecture, and may be used in a cluster
-Its own query language support
-Efficient transaction handling
-The Java Persistence API is the standard object/relational mapping and persistence management interface of the Java EE 5.0 platform which are implemented with the Hibernate Annotations and Hibernate EntityManager modules, on top of the Hibernate Core.(As part of EJB3.0 spec)
Why Hibernate?
The reasons are plenty,weighing in favor of Hibernate clearly.
-Cost effective.Just imagine when you are using EJBs instead of Hibernate.One has to invest in Application Server(Websphere,Weblogic etc.),learning curve for EJB is slow and requires special training if your developers are not equipped with the EJB know-how.
-The developers get rid of writing complex SQLs and no more need of JDBC APIs for resultset handling.Even less code than JDBC.In fact the OO developers work well when they have to deal with object then writing lousy queries.
-High performance then EJBs(if we go by their industry reputation),which itself a container managed,heavyweight solution.
-Switching to other SQL database requires few changes in Hibernate configuration file and requires least clutter than EJBs.
-EJB itself has modeled itself on Hibernate principle in its latest version i.e. EJB3 because of apparent reasons.
What is ORM ?
Object Relational Mapping(ORM) is a technique/solution that provides an object-based view of data to applications which it can manipulate.The basic purpose of ORM is to allow an application written in an object oriented language to deal with the information it manipulates in terms of objects, rather than in terms of database-specific concepts such as rows, columns and tables.
In the Java world, ORM's first appearance was under the form of entity beans. But entity beans have limited scope in Java EE domain,they can not be exploited for Java SE based applications.The mapping of class lever attributes is done to table columns.For example a String variabe of a class will directly map onto a VARCHAR column. A relationship mapping is the one that you use when you have an attribute of a class that holds a reference to an instance of some other class in your domain model. The most common types of relationship mappings are "one to one", "one to many" or "many to many".
What are core interfaces for Hibernate framework?
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.
[Source:Hibernate Reference Documentation]
Can you compare JDBC/DAO with Hibernate?
Hibernate and straight SQL through JDBC are different approaches.They both have their specific significance in different scenarios.If your application is not to big and complex,not too many tables and queries involved then it will be better to use JDBC. While Hibernate is a POJO based ORM tool,using JDBC underneath to connect to database, which lets one to get rid of writing SQLs and associated JDBC code to fetch resultset,meaning less LOC but more of configuration work.It will suit better when you have large application involving large volume of data and queries.Moreover lazy loading,caching of data helps in having better performance and you need not call the database every time rather data stays in object form which can be reused.
Explain different inheritance mapping models in Hibernate.
There can be three kinds of inheritance mapping in hibernate
1. Table per concrete class with unions
2. Table per class hierarchy
3. Table per subclass
Example:
We can take an example of three Java classes like Vehicle, which is an abstract class and two subclasses of Vehicle as Car and UtilityVan.
1. Table per concrete class with unions
In this scenario there will be 2 tables
Tables: Car, UtilityVan, here in this case all common attributes will be duplicated.
2. Table per class hierarchy
Single Table can be mapped to a class hierarchy
There will be only one table in database named 'Vehicle' which will represent all attributes required for all three classes.
Here it is be taken care of that discriminating columns to differentiate between Car and UtilityVan
3. Table per subclass
Simply there will be three tables representing Vehicle, Car and UtilityVan
Q. How will you configure Hibernate?
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 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.
Q. What is a SessionFactory? Is it a thread-safe object?
Answer:
SessionFactory is Hibernate’s 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.
SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();
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();
public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session
if(session == null) {
session = sessionFactory.openSession();
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.
Q. What are the benefits of detached objects?
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.
Q. What are the pros and cons of detached objects?
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?
Answer
• 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().
Q. What is the difference between the session.get() method and the session.load() method?
Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(…) returns null.
Q. What is the difference between the session.update() method and the session.lock() method?
Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.
Q. How would you reatach detached objects to a session when the same object has already been loaded into the session?
You can use the session.merge() method call.
Q. What are the general considerations or best practices for defining your Hibernate persistent classes?
1.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 persistable instance variables.
2.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.
3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.
4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.
5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.
Hibernate is a powerful, high performance object/relational persistence and query service.It is an open-source technology which fits well both with Java and .NET technologies.Hibernate lets developers write persistence classes with hibernate query features of HQL within principles of Object Oriented paradigm.It means one can include association,inheritance,polymorphism,composition and collection of these persisting objects to build applications.
Hibernate Architecture
The main objective of Hibernate is to relieve the developers from manual handling of SQLs,JDBC APIs for resultsets handling and it helps in keeping your data portable to various SQL databases,just by switching the delegate and driver details in hibernate.cfg.xml file.
Hibernate offers sophisticated query options, you can write plain SQL, object-oriented HQL (Hibernate Query Language), or create programmatic criteria and example queries. Hibernate can optimize object loading all the time, with various fetching and caching options.
Some snapshots of Hibernate:
-Free open source
-OO Concepts can be implemented.
-A rich variety of mappings for collections and dependent objects
-No extra code generation or bytecode processing steps in your build procedure
-Great performance, has a dual-layer cache architecture, and may be used in a cluster
-Its own query language support
-Efficient transaction handling
-The Java Persistence API is the standard object/relational mapping and persistence management interface of the Java EE 5.0 platform which are implemented with the Hibernate Annotations and Hibernate EntityManager modules, on top of the Hibernate Core.(As part of EJB3.0 spec)
Why Hibernate?
The reasons are plenty,weighing in favor of Hibernate clearly.
-Cost effective.Just imagine when you are using EJBs instead of Hibernate.One has to invest in Application Server(Websphere,Weblogic etc.),learning curve for EJB is slow and requires special training if your developers are not equipped with the EJB know-how.
-The developers get rid of writing complex SQLs and no more need of JDBC APIs for resultset handling.Even less code than JDBC.In fact the OO developers work well when they have to deal with object then writing lousy queries.
-High performance then EJBs(if we go by their industry reputation),which itself a container managed,heavyweight solution.
-Switching to other SQL database requires few changes in Hibernate configuration file and requires least clutter than EJBs.
-EJB itself has modeled itself on Hibernate principle in its latest version i.e. EJB3 because of apparent reasons.
What is ORM ?
Object Relational Mapping(ORM) is a technique/solution that provides an object-based view of data to applications which it can manipulate.The basic purpose of ORM is to allow an application written in an object oriented language to deal with the information it manipulates in terms of objects, rather than in terms of database-specific concepts such as rows, columns and tables.
In the Java world, ORM's first appearance was under the form of entity beans. But entity beans have limited scope in Java EE domain,they can not be exploited for Java SE based applications.The mapping of class lever attributes is done to table columns.For example a String variabe of a class will directly map onto a VARCHAR column. A relationship mapping is the one that you use when you have an attribute of a class that holds a reference to an instance of some other class in your domain model. The most common types of relationship mappings are "one to one", "one to many" or "many to many".
What are core interfaces for Hibernate framework?
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.
[Source:Hibernate Reference Documentation]
Can you compare JDBC/DAO with Hibernate?
Hibernate and straight SQL through JDBC are different approaches.They both have their specific significance in different scenarios.If your application is not to big and complex,not too many tables and queries involved then it will be better to use JDBC. While Hibernate is a POJO based ORM tool,using JDBC underneath to connect to database, which lets one to get rid of writing SQLs and associated JDBC code to fetch resultset,meaning less LOC but more of configuration work.It will suit better when you have large application involving large volume of data and queries.Moreover lazy loading,caching of data helps in having better performance and you need not call the database every time rather data stays in object form which can be reused.
Explain different inheritance mapping models in Hibernate.
There can be three kinds of inheritance mapping in hibernate
1. Table per concrete class with unions
2. Table per class hierarchy
3. Table per subclass
Example:
We can take an example of three Java classes like Vehicle, which is an abstract class and two subclasses of Vehicle as Car and UtilityVan.
1. Table per concrete class with unions
In this scenario there will be 2 tables
Tables: Car, UtilityVan, here in this case all common attributes will be duplicated.
2. Table per class hierarchy
Single Table can be mapped to a class hierarchy
There will be only one table in database named 'Vehicle' which will represent all attributes required for all three classes.
Here it is be taken care of that discriminating columns to differentiate between Car and UtilityVan
3. Table per subclass
Simply there will be three tables representing Vehicle, Car and UtilityVan
Q. How will you configure Hibernate?
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 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.
Q. What is a SessionFactory? Is it a thread-safe object?
Answer:
SessionFactory is Hibernate’s 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.
SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory();
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();
public static Session currentSession() throws HibernateException {
Session session = (Session) local.get();
//open a new session if this thread has no session
if(session == null) {
session = sessionFactory.openSession();
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.
Q. What are the benefits of detached objects?
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.
Q. What are the pros and cons of detached objects?
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?
Answer
• 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().
Q. What is the difference between the session.get() method and the session.load() method?
Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(…) returns null.
Q. What is the difference between the session.update() method and the session.lock() method?
Both of these methods and saveOrUpdate() method are intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction.
Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well.
Q. How would you reatach detached objects to a session when the same object has already been loaded into the session?
You can use the session.merge() method call.
Q. What are the general considerations or best practices for defining your Hibernate persistent classes?
1.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 persistable instance variables.
2.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.
3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.
4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.
5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.
How can I count the number of query results without actually returning them?
Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();
How can I find the size of a collection without initializing it?
Integer size = (Integer) s.createFilter( collection, "select count(*)" ).uniqueResult();
How can I order by the size of a collection?
Use a left join, together with group byselect user
from User user
left join user.messages msg
group by user
order by count(msg)
How can I place a condition upon a collection size?
If your database supports subselects:from User user where size(user.messages) >= 1or:
from User user where exists elements(user.messages)If not, and in the case of a one-to-many or many-to-many association:
select userBecause of the inner join, this form can't be used to return a User with zero messages, so the following form is also useful
from User user
join user.messages msg
group by user
having count(msg) >= 1
select user
from User as user
left join user.messages as msg
group by user
having count(msg) = 0
How can I query for entities with empty collections?
from Box boxOr, try this:
where box.balls is empty
select box
from Box box
left join box.balls ball
where ball is null
How can I sort / order collection elements?
There are three different approaches: 1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or or . This solution does a sort in memory.
2. Specify an order-byattribute of , or , naming a list of table columns to sort by. This solution works only in JDK 1.4+.
3. Use a filter session.createFilter( collection, "order by ...." ).list()
Are collections pageable?
Query q = s.createFilter( collection, "" ); // the trivial filter
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();
I have a one-to-one association between two classes. Ensuring that associated objects have matching identifiers is bugprone. Is there a better way?
parent
I have a many-to-many association between two tables, but the association table has some extra columns (apart from the foreign keys). What kind of mapping should I use?
Use a composite-element to model the association table. For example, given the following association table: create table relationship (you could use this collection mapping (inside the mapping for class Foo):
fk_of_foo bigint not null,
fk_of_bar bigint not null,
multiplicity smallint,
created date )
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 an MVC application, how can we ensure that all proxies and lazy collections will be initialized when the view tries to access them?
One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view. The session/transaction would be closed/committed after the view is rendered in, for example, a servlet filter (another example would by to use the ModelLifetime.discard()callback in Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view.Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is often more straightforward than it sounds.
How can I bind a dynamic list of values into an in query expression?
Query q = s.createQuery("from foo in class Foo where foo.id in (:id_list)");
q.setParameterList("id_list", fooIdList);
List foos = q.list();
How can I bind properties of a JavaBean to named query parameters?
Query q = s.createQuery("from foo in class Foo where foo.name=:name and foo.size=:size");
q.setProperties(fooBean); // fooBean has getName() and getSize()
List foos = q.list();
Can I map an inner class?
You may persist any static inner class. You should specify the class name using the standard form ie. eg.Foo$BarHow can I assign a default value to a property when the database column is null?
Use a UserType.How can I trucate Stringdata?
Use a UserType.How can I trim spaces from Stringdata persisted to a CHAR column?
Use a UserType.How can I convert the type of a property to/from the database column type?
Use a UserType.How can I get access to O/R mapping information such as table and column names at runtime?
This information is available via the Configurationobject. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory.How can I create an association to an entity without fetching that entity from the database (if I know the identifier)?
If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECTstatement:Item itemProxy = (Item) session.load(Item.class, itemId);
Bid bid = new Bid(user, amount, itemProxy);
session.save(bid);
How can I retrieve the identifier of an associated object, without fetching the association?
Just do it. The following code does not result in any SELECT statement, even if the item association is lazy.Long itemId = bid.getItem().getId();This works if getItem()returns a proxy and if you mapped the identifier property with regular accessor methods. If you enabled direct field access for the id of an Item, the Item proxy will be initialized if you call getId(). This method is then treated like any other business method of the proxy, initialization is required if it is called.
How can I manipulate mappings at runtime?
You can access (and modify) the Hibernate metamodel via the Configuration object, using getClassMapping(), getCollectionMapping(), etc.Note that the SessionFactoryis 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.
How can I avoid n+1 SQL SELECTqueries 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.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 UserTypeto perform binding to/from the PreparedStatement.
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.More Hibernate Questions
Answer: 1. By placing hibernate.properties file in the classpath.
2. Including elements in hibernate.cfg.xml in the classpath.
Question:How can you create a primary key using Hibernate?
Answer: The 'id' tag in .hbm file corresponds to primary key of the table:
Here Id ="empid", that will act as primary key of the table "EMPLOYEE".
Question: In how many ways one can map files to be configured in Hibernate?
Answer: 1. Either mapping files are added to configuration in the application code or,
2.hibernate.cfg.xml can be used for configuring in .
Question: How to set Hibernate to log all generated SQL to the console?
Answer: By setting the hibernate.show_sql property to true.
Question: What happens when both hibernate.properties and hibernate.cfg.xmlare in the classpath?
Answer: The settings of the XML configuration file will override the settings used in the properties.
Question: What methods must the persistent classes implement in Hibernate?
Answer: Since Hibernate instantiates persistent classes using Constructor.newInstance(), it requires a constructor with no arguments for every persistent class. And getter and setter methods for all the instance variables.
Question: How can Hibernate be configured to access an instance variable directly and not through a setter method?
Answer: 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.
Question: How to declare mappings for multiple classes in one mapping file?
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?
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:
8.What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
- Programmatic configuration
- XML configuration (
hibernate.cfg.xml
)
9.What are the important tags of hibernate.cfg.xml?
An Action Class is an adapter between the contents of an incoming HTTP rest and the corresponding business logic that should be executed to process this rest.
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
11.What role does the Session interface play in Hibernate?
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();
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 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
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.What’s the difference between load() and get()?
load() vs. get() :-
load() | get() |
Only use the load() method if you are sure that the object exists. | If you are not sure that the object exists, then use one of the get() methods. |
load() method will throw an exception if the unique id is not found in the database. | get() method will return null if the unique id is not found in the database. |
load() just returns a proxy by default and database won’t be hit until the proxy is first invoked. | get() will hit the database immediately. |
17.What is the difference between and merge and update ?
Use
update()
if you are sure that the session does not contain an already persistent instance with the same identifier, and merge()
if you want to merge your modifications at any time without consideration of the state of the session.19.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
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?
20.What does it mean to be inverse?
It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse then a child–>parent relationship would be created.
23.Explain Criteria API
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
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?
20.What does it mean to be inverse?
It informs hibernate to ignore that end of the relationship. If the one–to–many was marked as inverse, hibernate would create a child–>parent relationship (child.getParent). If the one–to–many was marked as non–inverse 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 :
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.HibernateTemplate
is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.25.What are the benefits does HibernateTemplate provide?
The benefits of HibernateTemplate are :
HibernateTemplate
, a Spring Template class simplifies interactions with Hibernate Session.- Common functions are simplified to single method calls.
- Sessions are automatically closed.
- Exceptions are automatically caught and converted to runtime exceptions.
26.How do you switch between relational databases without code changes?
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
27.If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
true
28.What are derived properties?
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.
29.What is component mapping in Hibernate?
Using Hibernate SQL Dialects , we can switch databases. Hibernate will generate appropriate hql queries based on the dialect defined.
27.If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
true
28.What are derived properties?
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.
29.What is component mapping in Hibernate?
- A component is an object saved as a value, not as a reference
- A component can be saved directly without needing to declare interfaces or identifier properties
- Required to define an empty constructor
- Shared references not supported
Example:
30.What is the difference between sorted and ordered collection in hibernate? sorted collection vs. order collection :-
sorted collection | order collection |
A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs in the memory of JVM which running Hibernate, after the data being read from database using java comparator. | Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval. |
If your collection is not large, it will be more efficient way to sort it. | If your collection is very large, it will be 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 map an object model's data representation to a relational data model and its corresponding database schema. | Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this. |
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. | Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS. |
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task. | Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application. |
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. | Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties. |
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. | Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost. |
With JDBC, caching is maintained by hand-coding. | Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. |
In JDBC there is no check that always every user has updated data. This check has to be added by the developer. | Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version 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
33.What are the ways to express joins in HQL?
HQL provides four ways of expressing (inner and outer) joins:-
* An implicit association join
* An ordinary join in the FROM clause
* A fetch join in the FROM clause.
* A theta-style join in the WHERE clause.
34.Define cascade and inverse option in one-many mapping?
cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"
inverse - mark this collection as the "inverse" end of a bidirectional association.
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 object—for 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 |
Session–Cache or collection of loaded objects relating to a single unit of work | Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit |
XDoclet Annotations used to support Attribute Oriented Programming | Java 5.0 Annotations used to support Attribute Oriented Programming |
Defines HQL for expressing queries to the database | Defines EJB QL for expressing queries |
Supports Entity Relationships through mapping files and annotations in JavaDoc | Support Entity Relationships through Java 5.0 annotations |
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API | Provides and Entity Manager Interface for managing CRUD operations for an Entity |
Provides callback support through lifecycle, interceptor, and validatable interfaces | Provides callback support through Entity Listener and Callback methods |
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships | Entity Relationships are bidirectional or unidirectional |
45.What are the types of inheritance models in Hibernate?
There are three types of inheritance models in Hibernate:
- Table per class hierarchy
- Table per subclass
- Table per concrete class
Hibernate Vs. iBatis?
Hibernate or iBatis or both ? Which is better?
Which one to use and when?
These are the few questions that continuously get asked in most of forums.
What’s really difference between two and really more importantly when should I use one over the other. Its pretty interesting question because there are major differences between iBatis and Hibernate.
Within in the java persistence there is no one size, fits all solution. So, in this case Hibernate which is a de facto standard is used in lot of places.
Let us consider a scenario where Hibernate work great for initial model. Now Suddenly if you are using stored procedures, well we can do it in Hibernate but its little difficult; ok we map those, all of sudden we got some reporting type of queries, those don’t have keys have group bys; with some difficulty here we can use name queries and stuff like that, but now starts getting more complicated, we have complex joins, yes you can do in hibernate, but we can’t do with average developer. We have sql that just doesn’t work.
So these are some of the complexities. One of the other things I find is, if am looking at an application that doesn’t work very well with an ORM, aside from these considerations of using stored procedures, already using SQL, complex joins. In other words, Hibernate works very well if your data model is well in sync with object model, because ORM solutions like Hibernate map object to tables. However, let’s suppose data model is not in sync with object model, in this case you have do lot of additional coding and complexities are entering into your application, start coming the beyond the benefits of ORM. So, again all of sudden you are noticing that the flow is gone; our application is becoming very very complex and developers can’t maintain the code.
This is where the model starts breaking down. One size does not fit all. So this is where I like to use iBatis; as the alternative solution for these type of situations, iBatis maps results sets to objects, so 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? That’s 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 doesn’t break the transactional model, and it doesn’t affect any of the primary & secondary caches with a Hibernate. It’s 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 isn’t 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.
Hibernate or iBatis or both ? Which is better?
Which one to use and when?
These are the few questions that continuously get asked in most of forums.
What’s really difference between two and really more importantly when should I use one over the other. Its pretty interesting question because there are major differences between iBatis and Hibernate.
Within in the java persistence there is no one size, fits all solution. So, in this case Hibernate which is a de facto standard is used in lot of places.
Let us consider a scenario where Hibernate work great for initial model. Now Suddenly if you are using stored procedures, well we can do it in Hibernate but its little difficult; ok we map those, all of sudden we got some reporting type of queries, those don’t have keys have group bys; with some difficulty here we can use name queries and stuff like that, but now starts getting more complicated, we have complex joins, yes you can do in hibernate, but we can’t do with average developer. We have sql that just doesn’t work.
So these are some of the complexities. One of the other things I find is, if am looking at an application that doesn’t work very well with an ORM, aside from these considerations of using stored procedures, already using SQL, complex joins. In other words, Hibernate works very well if your data model is well in sync with object model, because ORM solutions like Hibernate map object to tables. However, let’s suppose data model is not in sync with object model, in this case you have do lot of additional coding and complexities are entering into your application, start coming the beyond the benefits of ORM. So, again all of sudden you are noticing that the flow is gone; our application is becoming very very complex and developers can’t maintain the code.
This is where the model starts breaking down. One size does not fit all. So this is where I like to use iBatis; as the alternative solution for these type of situations, iBatis maps results sets to objects, so 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? That’s 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 doesn’t break the transactional model, and it doesn’t affect any of the primary & secondary caches with a Hibernate. It’s 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 isn’t 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
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 objects—known as singletons—are 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:- Ensure that only one instance of a class is created
- Provide a global point of access to the object
- Allow multiple instances in the future without affecting a singleton class's clients
Note: You can download this article's source code from Resources.
The Singleton pattern
In Design Patterns, the authors describe the Singleton pattern like this: Ensure a class has only one instance, and provide a global point of access to it.
Singleton class diagram
As you can see from the figure above, there's not a whole lot to the Singleton design pattern. Singletons maintain a static reference to the sole singleton instance and return a reference to that instance from a static instance()
method. Example 1 shows a classic Singleton design pattern implementation:
Example 1. The classic singleton
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
}
ClassicSingleton
class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance()
method. There are several interesting points concerning the
ClassicSingleton
class. First, ClassicSingleton
employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance()
method is called for the first time. This technique ensures that singleton instances are created only when needed. Second, notice that
ClassicSingleton
implements a protected constructor so clients cannot instantiate ClassicSingleton
instances; however, you may be surprised to discover that the following code is perfectly legal: public class SingletonInstantiator {
public SingletonInstantiator() {
ClassicSingleton instance = ClassicSingleton.getInstance();
ClassicSingleton anotherInstance =
new ClassicSingleton();
...
}
}
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 ClassicSingleton
instances. This dilemma has two solutions: You can make the ClassicSingleton
constructor private so that only ClassicSingleton()
methods call it; however, that means ClassicSingleton
cannot 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
ClassicSingleton
implements the java.io.Serializable
interface, 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 threads—we'll call them Thread 1 and Thread 2—call ClassicSingleton.getInstance()
at the same time, two ClassicSingleton
instances 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.
StringBuffer versus String
What is the performance impact of the StringBuffer and String classes?
Java provides the
StringBuffer
and String
classes, and the String
class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String
are read only and immutable. The StringBuffer
class is used to represent characters that can be modified.The significant performance difference between these two classes is that
StringBuffer
is faster than String
when performing simple concatenations. In String
manipulation code, character strings are routinely concatenated. Using the String
class, concatenations are typically performed as follows: String str = new String ("Stanford ");
str += "Lost!!";
StringBuffer
to perform the same concatenation, you would need code that looks like this: StringBuffer str = new StringBuffer ("Stanford ");
str.append("Lost!!");
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 String
looks 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
String str = new String("Stanford ");
str += "Lost!!";
StringBuffer
object, then invokes its append
method: the temporary StringBuffer
object is created at location 10, and its append
method is called at location 23. Because the String
class is immutable, a StringBuffer
must 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 String
object from the temporary StringBuffer
object. The creation of this temporary StringBuffer
object 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:
- A
String
object at location 0 - A
StringBuffer
object at location 10 - A
String
object at location 26
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
StringBuffer str = new StringBuffer("Stanford ");
str.append("Lost!!");
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,
StringBuffer
concatenation is significantly faster than String
concatenation. Obviously, StringBuffer
s should be used in this type of operation when possible. If the functionality of the String
class is desired, consider using a StringBuffer
for concatenation and then performing one conversion to String
. Difference between JDBC and hibernate
1) Hibernate is data base independent, your code will work for all ORACLE,MySQL ,SQLServer etc.
In case of JDBC query must be data base specific.
2) As Hibernate is set of Objects , you don?t need to learn SQL language.
You can treat TABLE as a Object . Only Java knowledge is need.
In case of JDBC you need to learn SQL.
3) Don?t need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.
In case of JDBC you need to tune your queries.
4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.
In case of JDBC you need to implement your java cache .
5) Hibernate supports Query cache and It will provide the statistics about your query and database status.
JDBC Not provides any statistics.
6) Development fast in case of Hibernate because you don?t need to write queries
7) No need to create any connection pool in case of Hibernate. You can use c3p0.
In case of JDBC you need to write your own connection pool
8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.
9) You can load your objects on start up using lazy=false in case of Hibernate.
JDBC Don?t have such support.
10 ) Hibernate Supports automatic versioning of rows but JDBC Not.
In case of JDBC query must be data base specific.
2) As Hibernate is set of Objects , you don?t need to learn SQL language.
You can treat TABLE as a Object . Only Java knowledge is need.
In case of JDBC you need to learn SQL.
3) Don?t need Query tuning in case of Hibernate. If you use Criteria Quires in Hibernate then hibernate automatically tuned your query and return best result with performance.
In case of JDBC you need to tune your queries.
4) You will get benefit of Cache. Hibernate support two level of cache. First level and 2nd level. So you can store your data into Cache for better performance.
In case of JDBC you need to implement your java cache .
5) Hibernate supports Query cache and It will provide the statistics about your query and database status.
JDBC Not provides any statistics.
6) Development fast in case of Hibernate because you don?t need to write queries
7) No need to create any connection pool in case of Hibernate. You can use c3p0.
In case of JDBC you need to write your own connection pool
8) In the xml file you can see all the relations between tables in case of Hibernate. Easy readability.
9) You can load your objects on start up using lazy=false in case of Hibernate.
JDBC Don?t have such support.
10 ) Hibernate Supports automatic versioning of rows but JDBC Not.
What's the difference between "PreparedStatement" and "Statement"?
PreparedStatements are useful when you have one query to execute several times with just parameters changed. In normal case each and every query has to be checked by database whether syntax is ok or not. SQL Statement are precomplied and stored in PreparedStatement object, so it saves time of database to check its syntax.
· The
PreparedStatement
is a slightly more powerful version of a Statement
, and should always be at least as quick and easy to handle as a Statement
. - Parse the incoming SQL query
- Compile the SQL query
- Plan/optimize the data acquisition path
- Execute the optimized query / acquire and return data
A
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.Statement
will always proceed through the four steps above for each SQL query sent to the database. A PreparedStatement
pre-executes steps (1) - (3) in the execution process above. Thus, when creating a PreparedStatement
some pre-optimization is performed immediately. The effect is to lessen the load on the database engine at execution time.Use the set methods each time to specify new parameter values.
Hibernate Interview Questions and Answers
Q. How will you configure Hibernate?
A. 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 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.
Q. What is a SessionFactory? Is it a thread-safe object?
A. SessionFactory is Hibernate's 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.
SessionFactory sessionFactory = new Configuration( ).configure( ).buildSessionfactory( );
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 4 5 6 7 8 9 10 11 12 13 14 | public class HibernateUtil { public static final ThreadLocal local = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session session = (Session) local.get(); //open a new session if this thread has no session if(session == null) { session = sessionFactory.openSession(); 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. 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.
Q. What are the benefits of detached objects?
A.
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 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.
Q. When does an object become detached?
A.
1 2 3 | Session session1 = sessionFactory.openSession(); Car myCar = session1.get(Car.class, carId); //”myCar” is a persistent object at this stage. session1.close(); //once the session is closed “myCar” becomes a detached object |
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”); //no effect on the database |
When you are ready to persist this change to the database, it can be reattached to another session as shown below:
1 2 3 4 5 | Session session2 = sessionFactory.openSession(); Transaction tx = session2.beginTransaction(); session2.update(myCar); //detached object ”myCar” gets re-attached tx.commit(); //change is synchronized with the database. session2.close() |
Q. 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( ).
Note: When you reattach detached objects, you need to make sure that the dependent objects are reattached as well.
Hibernate Interview Questions
1. Does Hibernate implement its functionality using a minimal number of database queries to ensure optimal output?
Hibernate can make certain optimizations all the time:
• Caching objects - The session is a transaction-level cache of persistent objects. You may also enable a JVM-level/cluster cache to memory and/or local disk.
• Executing SQL statements later, when needed - The session never issues an INSERT or UPDATE until it is actually needed. So if an exception occurs and you need to abort the transaction, some statements will never actually be issued. Furthermore, this keeps lock times in the database as short as possible (from the late UPDATE to the transaction end).
• Never updating unmodified objects - It is very common in hand-coded JDBC to see the persistent state of an object updated, just in case it changed.....for example, the user pressed the save button but may not have edited any fields. Hibernate always knows if an object's state actually changed, as long as you are inside the same (possibly very long) unit of work.
• Efficient Collection Handling - Likewise, Hibernate only ever inserts/updates/deletes collection rows that actually changed.
• Rolling two updates into one - As a corollary to (1) and (3), Hibernate can roll two seemingly unrelated updates of the same object into one UPDATE statement.
• Updating only the modified columns - Hibernate knows exactly which columns need updating and, if you choose, will update only those columns.
• Outer join fetching - Hibernate implements a very efficient outer-join fetching algorithm! In addition, you can use subselect and batch pre-fetch optimizations.
• Lazy collection initialization
• Lazy object initialization - Hibernate can use runtime-generated proxies (CGLIB) or interception injected through byte code instrumentation at build-time.
2. Why not implement instance-pooling in Hibernate?
Firstly, it would be pointless. There is a lower bound to the amount of garbage Hibernate creates every time it loads or updates and object - the garbage created by getting or setting the object's properties using reflection.
More importantly, the disadvantage of instance-pooling is developers who forget to reinitialize fields each time an instance is reused. We have seen very subtle bugs in EJBs that don't reinitialize all fields in ejbCreate.
On the other hand, if there is a particular application object that is extremely expensive to create, you can easily implement your own instance pool for that class and use the version of Session.load() that takes a class instance. Just remember to return the objects to the pool every time you close the session.
3. Does Hibernate use runtime reflection?
Many former C or C++ programmers prefer generated-code solutions to runtime reflection. This is usually justified by reference to the performance red-herring. However, modern JVMs implement reflection extremely efficiently and the overhead is minimal compared to the cost of disk access or IPC. Developers from other traditions (e.g. Smalltalk) have always relied upon reflection to do things that C/C++ needs code-generation for.
In the very latest versions of Hibernate, "reflection" is optimised via the CGLIB runtime byte code generation library. This means that "reflected" property get / set calls no longer carry the overhead of the Java reflection API and are actually just normal method calls. This results in a (very) small performance gain.
4. How do I use Hibernate in an EJB 2.1 session bean?
1. Look up the SessionFactory in JNDI.
2. Call getCurrentSession() to get a Session for the current transaction.
3. Do your work.
4. Don't commit or close anything, let the container manage the transaction.
5. What’s the easiest way to configure Hibernate in a plain Java application (without using JNDI)?
Build a SessionFactory from a Configuration object.
6. What is Middlegen?
Middlegen is an open source code generation framework that provides a general-purpose database-driven engine using various tools such as JDBC, Velocity, Ant and XDoclet.
7. How can I count the number of query results without actually returning them?
Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();
8. How can I find the size of a collection without initializing it?
Integer size = (Integer) s.createFilter( collection, "select count(*)" ).uniqueResult();
9. How can I order by the size of a collection?
Use a left join, together with group by
select user
from User user
left join user.messages msg
group by user
order by count(msg)
10. How can I place a condition upon a collection size?
If your database supports subselects:
from User user where size(user.messages) >= 1
or:
from User user where exists elements(user.messages)
If not, and in the case of a one-to-many or many-to-many association:
select user
from User user
join user.messages msg
group by user
having count(msg) >= 1
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
11. How can I query for entities with empty collections?
from Box box
where box.balls is empty
Or, try this:
select box
from Box box
left join box.balls ball
where ball is null
12. How can I sort / order collection elements?
There are three different approaches:
1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or < set > or < map >. This solution does a sort in memory.
2. Specify an order-by attribute of < set >, < map > or < bag >, naming a list of table columns to sort by. This solution works only in JDK 1.4+.
3. Use a filter session.createFilter( collection, "order by ...." ).list()
13. Are collections pageable?
Query q = s.createFilter( collection, "" );
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();
I have a one-to-one association between two classes. Ensuring that associated objects have matching identifiers is bug-prone. Is there a better way?
< generator class="foreign" >
< param name="property" > parent < / param >
< / generator >
I have a many-to-many association between two tables, but the association table has some extra columns (apart from the foreign keys). What kind of mapping should I use?
Use a composite-element to model the association table. For example, given the following association table:
create table relationship (
fk_of_foo bigint not null,
fk_of_bar bigint not null,
multiplicity smallint,
created date )
you could use this collection mapping (inside the mapping for class Foo):
< set name="relationship" >
< key column="fk_of_foo" / >
< composite-element class="Relationship" >
< property name="multiplicity" type="short" not-null="true" / >
< property name="created" type="date" not-null="true" / >
< many-to-one name="bar" class="Bar" not-null="true" / >
< / composite-element >
< / set >
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 an MVC application, how can we ensure that all proxies and lazy collections will be initialized when the view tries to access them?
One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view. The session/transaction would be closed/committed after the view is rendered in, for example, a Servlet filter (another example would by to use the ModelLifetime.discard() callback in Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view.
Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is often more straightforward than it sounds.
14. How can I bind a dynamic list of values into an in query expression?
Query q = s.createQuery("from foo in class Foo where foo.id in (:id_list)");
q.setParameterList("id_list", fooIdList);
List foos = q.list();
15. How can I bind properties of a JavaBean to named query parameters?
Query q = s.createQuery("from foo in class Foo where foo.name=:name and foo.size=:size");
q.setProperties(fooBean); // fooBean has getName() and getSize()
List foos = q.list();
16. Can I map an inner class?
You may persist any static inner class. You should specify the class name using the standard form i.e. eg.Foo$Bar
17. How can I assign a default value to a property when the database column is null?
Use a UserType.
18. How can I truncate String data?
Use a UserType.
19. How can I trim spaces from String data persisted to a CHAR column?
Use a UserType.
20. How can I convert the type of a property to/from the database column type?
Use a UserType.
21. How can I get access to O/R mapping information such as table and column names at runtime?
This information is available via the Configuration object. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory.
22. How can I create an association to an entity without fetching that entity from the database (if I know the identifier)?
If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECT statement:
Item itemProxy = (Item) session.load(Item.class, itemId);
Bid bid = new Bid(user, amount, itemProxy);
session.save(bid);
23. How can I retrieve the identifier of an associated object, without fetching the association?
Just do it. The following code does not result in any SELECT statement, even if the item association is lazy.
Long itemId = bid.getItem().getId();
This works if getItem() returns a proxy and if you mapped the identifier property with regular accessor methods. If you enabled direct field access for the id of an Item, the Item proxy will be initialized if you call getId(). This method is then treated like any other business method of the proxy, initialization is required if it is called.
24. How can I manipulate mappings at runtime?
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).
Hibernate can make certain optimizations all the time:
• Caching objects - The session is a transaction-level cache of persistent objects. You may also enable a JVM-level/cluster cache to memory and/or local disk.
• Executing SQL statements later, when needed - The session never issues an INSERT or UPDATE until it is actually needed. So if an exception occurs and you need to abort the transaction, some statements will never actually be issued. Furthermore, this keeps lock times in the database as short as possible (from the late UPDATE to the transaction end).
• Never updating unmodified objects - It is very common in hand-coded JDBC to see the persistent state of an object updated, just in case it changed.....for example, the user pressed the save button but may not have edited any fields. Hibernate always knows if an object's state actually changed, as long as you are inside the same (possibly very long) unit of work.
• Efficient Collection Handling - Likewise, Hibernate only ever inserts/updates/deletes collection rows that actually changed.
• Rolling two updates into one - As a corollary to (1) and (3), Hibernate can roll two seemingly unrelated updates of the same object into one UPDATE statement.
• Updating only the modified columns - Hibernate knows exactly which columns need updating and, if you choose, will update only those columns.
• Outer join fetching - Hibernate implements a very efficient outer-join fetching algorithm! In addition, you can use subselect and batch pre-fetch optimizations.
• Lazy collection initialization
• Lazy object initialization - Hibernate can use runtime-generated proxies (CGLIB) or interception injected through byte code instrumentation at build-time.
2. Why not implement instance-pooling in Hibernate?
Firstly, it would be pointless. There is a lower bound to the amount of garbage Hibernate creates every time it loads or updates and object - the garbage created by getting or setting the object's properties using reflection.
More importantly, the disadvantage of instance-pooling is developers who forget to reinitialize fields each time an instance is reused. We have seen very subtle bugs in EJBs that don't reinitialize all fields in ejbCreate.
On the other hand, if there is a particular application object that is extremely expensive to create, you can easily implement your own instance pool for that class and use the version of Session.load() that takes a class instance. Just remember to return the objects to the pool every time you close the session.
3. Does Hibernate use runtime reflection?
Many former C or C++ programmers prefer generated-code solutions to runtime reflection. This is usually justified by reference to the performance red-herring. However, modern JVMs implement reflection extremely efficiently and the overhead is minimal compared to the cost of disk access or IPC. Developers from other traditions (e.g. Smalltalk) have always relied upon reflection to do things that C/C++ needs code-generation for.
In the very latest versions of Hibernate, "reflection" is optimised via the CGLIB runtime byte code generation library. This means that "reflected" property get / set calls no longer carry the overhead of the Java reflection API and are actually just normal method calls. This results in a (very) small performance gain.
4. How do I use Hibernate in an EJB 2.1 session bean?
1. Look up the SessionFactory in JNDI.
2. Call getCurrentSession() to get a Session for the current transaction.
3. Do your work.
4. Don't commit or close anything, let the container manage the transaction.
5. What’s the easiest way to configure Hibernate in a plain Java application (without using JNDI)?
Build a SessionFactory from a Configuration object.
6. What is Middlegen?
Middlegen is an open source code generation framework that provides a general-purpose database-driven engine using various tools such as JDBC, Velocity, Ant and XDoclet.
7. How can I count the number of query results without actually returning them?
Integer count = (Integer) session.createQuery("select count(*) from ....").uniqueResult();
8. How can I find the size of a collection without initializing it?
Integer size = (Integer) s.createFilter( collection, "select count(*)" ).uniqueResult();
9. How can I order by the size of a collection?
Use a left join, together with group by
select user
from User user
left join user.messages msg
group by user
order by count(msg)
10. How can I place a condition upon a collection size?
If your database supports subselects:
from User user where size(user.messages) >= 1
or:
from User user where exists elements(user.messages)
If not, and in the case of a one-to-many or many-to-many association:
select user
from User user
join user.messages msg
group by user
having count(msg) >= 1
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
11. How can I query for entities with empty collections?
from Box box
where box.balls is empty
Or, try this:
select box
from Box box
left join box.balls ball
where ball is null
12. How can I sort / order collection elements?
There are three different approaches:
1. Use a SortedSet or SortedMap, specifying a comparator class in the sort attribute or < set > or < map >. This solution does a sort in memory.
2. Specify an order-by attribute of < set >, < map > or < bag >, naming a list of table columns to sort by. This solution works only in JDK 1.4+.
3. Use a filter session.createFilter( collection, "order by ...." ).list()
13. Are collections pageable?
Query q = s.createFilter( collection, "" );
q.setMaxResults(PAGE_SIZE);
q.setFirstResult(PAGE_SIZE * pageNumber);
List page = q.list();
I have a one-to-one association between two classes. Ensuring that associated objects have matching identifiers is bug-prone. Is there a better way?
< generator class="foreign" >
< param name="property" > parent < / param >
< / generator >
I have a many-to-many association between two tables, but the association table has some extra columns (apart from the foreign keys). What kind of mapping should I use?
Use a composite-element to model the association table. For example, given the following association table:
create table relationship (
fk_of_foo bigint not null,
fk_of_bar bigint not null,
multiplicity smallint,
created date )
you could use this collection mapping (inside the mapping for class Foo):
< set name="relationship" >
< key column="fk_of_foo" / >
< composite-element class="Relationship" >
< property name="multiplicity" type="short" not-null="true" / >
< property name="created" type="date" not-null="true" / >
< many-to-one name="bar" class="Bar" not-null="true" / >
< / composite-element >
< / set >
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 an MVC application, how can we ensure that all proxies and lazy collections will be initialized when the view tries to access them?
One possible approach is to leave the session open (and transaction uncommitted) when forwarding to the view. The session/transaction would be closed/committed after the view is rendered in, for example, a Servlet filter (another example would by to use the ModelLifetime.discard() callback in Maverick). One difficulty with this approach is making sure the session/transaction is closed/rolled back if an exception occurs rendering the view.
Another approach is to simply force initialization of all needed objects using Hibernate.initialize(). This is often more straightforward than it sounds.
14. How can I bind a dynamic list of values into an in query expression?
Query q = s.createQuery("from foo in class Foo where foo.id in (:id_list)");
q.setParameterList("id_list", fooIdList);
List foos = q.list();
15. How can I bind properties of a JavaBean to named query parameters?
Query q = s.createQuery("from foo in class Foo where foo.name=:name and foo.size=:size");
q.setProperties(fooBean); // fooBean has getName() and getSize()
List foos = q.list();
16. Can I map an inner class?
You may persist any static inner class. You should specify the class name using the standard form i.e. eg.Foo$Bar
17. How can I assign a default value to a property when the database column is null?
Use a UserType.
18. How can I truncate String data?
Use a UserType.
19. How can I trim spaces from String data persisted to a CHAR column?
Use a UserType.
20. How can I convert the type of a property to/from the database column type?
Use a UserType.
21. How can I get access to O/R mapping information such as table and column names at runtime?
This information is available via the Configuration object. For example, entity mappings may be obtained using Configuration.getClassMapping(). It is even possible to manipulate this metamodel at runtime and then build a new SessionFactory.
22. How can I create an association to an entity without fetching that entity from the database (if I know the identifier)?
If the entity is proxyable (lazy="true"), simply use load(). The following code does not result in any SELECT statement:
Item itemProxy = (Item) session.load(Item.class, itemId);
Bid bid = new Bid(user, amount, itemProxy);
session.save(bid);
23. How can I retrieve the identifier of an associated object, without fetching the association?
Just do it. The following code does not result in any SELECT statement, even if the item association is lazy.
Long itemId = bid.getItem().getId();
This works if getItem() returns a proxy and if you mapped the identifier property with regular accessor methods. If you enabled direct field access for the id of an Item, the Item proxy will be initialized if you call getId(). This method is then treated like any other business method of the proxy, initialization is required if it is called.
24. How can I manipulate mappings at runtime?
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:
- API for performing basic CRUD operations
- API to express queries 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
- High-level object-oriented API
- Less Java code to write
- No SQL to write
- Improved performance
- Sophisticated caching
- Lazy loading
- Eager loading
- Improved maintainability
- A lot less code to write
- Improved portability
- 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:
8.What are the most common methods of Hibernate configuration?
The most common methods of Hibernate configuration are:
- Programmatic configuration
- XML configuration (
hibernate.cfg.xml
)
9.What are the important tags of hibernate.cfg.xml?
Following are the important tags of hibernate.cfg.xml:
10.What are the Core interfaces are of Hibernate framework?
People who read this, also read:- |
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
|
11.What role does the Session interface play in Hibernate?
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();
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 applicationÃ¥¹¼reated 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).
- 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>
No comments:
Post a Comment