1.Why do you need ORM tools like hibernate?
Ans: The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:
Improved productivity
A lot less code to write
Improved portability
ORM framework generates database-specific SQL for you
2.What Does Hibernate Simplify?
Ans: Hibernate simplifies:
3. What’s the difference between load() and get()?
Ans: load() vs. get() :-
load() get()
Only use the load() method if you are sure If you are not sure that the object exists, then use one that the object exists. of the get() methods.
load() method will throw an exception if get() method will return null if the unique id is not the unique id is not found in the database. found in the database.
load() just returns a proxy by default and get() will hit the database immediately.
database won’t be hit until the proxy is first
invoked.
4. What is the difference between and merge and update ?
Ans: 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.
5. Define cascade and inverse option in one-many mapping?
Ans: 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?
6. What is lazy Initializing?
7.What does it mean to be inverse?
Ans: 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.
8. Explain Criteria API
Ans: Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example : List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();
9.What are the differences between EJB 3.0 & Hibernate
Ans:
Hibernate Vs EJB 3.0 :-
Hibernate EJB 3.0
Session–Cache or collection of loaded objects Persistence Context-Set of entities that can be relating to a single unit of work managed by a given EntityManager is defined by a persistence unit
XDoclet Annotations used to support Attribute Java 5.0 Annotations used to support Attribute Oriented Programming Oriented Programming
Defines HQL for expressing queries to the Defines EJB QL for expressing queries
database
Supports Entity Relationships through mapping Support Entity Relationships through Java 5.0 files and annotations in JavaDoc annotations
Provides a Persistence Manager API exposed Provides and Entity Manager Interface for
via the Session, Query, Criteria, and managing CRUD operations for an Entity
Transaction API
Provides callback support through lifecycle, Provides callback support through Entity Listener and interceptor, and validatable interfaces Callback methods
Entity Relationships are unidirectional. Entity Relationships are bidirectional or Bidirectional relationships are implemented by unidirectional
two unidirectional relationships
10. What is Lazy Initializing? When do you receive an LazyInitialization Exception?
11. Filter in Hibernate with Example?
Ans:
USER ( ID INT, USERNAME VARCHAR, ACTIVATED BOOLEAN) - TABLE
public class User
{
private int id;
private String username;
private boolean activated;
public boolean isActivated()
{
return activated;
}
public void setActivated(boolean activated)
{
this.activated = activated;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}
-----------------------------------------------------------------
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User">
<id name="id" >
<generator />
</id>
<property name="username" length="32"/>
<property name="activated" />
<filter name="activatedFilter" condition=":activatedParam = activated"/>
</class>
<filter-def name="activatedFilter">
<filter-param name="activatedParam" />
</filter-def>
</hibernate-mapping>
--------------------------------------------------------------------
Save and Fetch using filter example
User user1 = new User();
user1.setUsername("name1");
user1.setActivated(false);
session.save(user1);
User user2 = new User();
user2.setUsername("name2");
user2.setActivated(true);
session.save(user2);
User user3 = new User();
user3.setUsername("name3");
user3.setActivated(true);
session.save(user3);
User user4 = new User();
user4.setUsername("name4");
user4.setActivated(false);
session.save(user4);
All the four user saved to Data Base User Table.
Now Fetch the User using Filter..
Filter filter = session.enableFilter("activatedFilter");
filter.setParameter("activatedParam",new Boolean(true));
Query query = session.createQuery("from User");
Iterator results = query.iterate();
while (results.hasNext())
{
User user = (User) results.next();
System.out.print(user.getUsername() + " is ");
}
Guess the Result :
name2
name3
Because Filer is filtering ( only true value) data before query execute.
12. EhCache is used for 2nd level cache to store all the redefind data like country table ..
Ans:
When you are creating SessionFactory just add the below steps
String ecache = appHome+File.separatorChar+"ehcache.xml";
try {
CacheManager.create(ecache);
} catch (CacheException e) {
// logger.logError(e);
}*/
Then
sessionFactory = configuration.buildSessionFactory();
ECache.xml is like
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="bean.ApplicationBean"
maxElementsInMemory="300"
eternal="false"
overflowToDisk="false"
/>
</ehcache>
ApplicationBean will be avilable in 2nd level cache.
13. How to handle user think time using hibernate ?
Ans: version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time)
and in the same time User B edit the same record for update and click the update. Then User A click the Update and update done. Chnage made by user B is gone. In hibernate you can perevent slate object updatation using version checking. Check the version of the row when you are upding the row. Get the version of the row when you are fetching the row of the TABLE for update. On the time of updation just fetch the version number and match with your version number ( on the time of fetching). This way you can prevent slate object updatation.
Step 1:
Declare a variable "versionId" in your Class with setter and getter.
public class Campign {
private Long versionId;
private Long campignId;
private String name;
public Long getVersionId() {
return versionId;
}
public void setVersionId(Long versionId) {
this.versionId = versionId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCampignId() {
return campignId;
}
private void setCampignId(Long campignId) {
this.campignId = campignId;
}
}
Step 2:
In the .hbm.xml file
<class name="beans.Campign" table="CAMPIGN" optimistic-lock="version">
<id name="campignId" column="cid">
<generator >
<param name="sequence">CAMPIGN_ID_SEQ</param>
</generator>
</id>
<version name="versionId" column="version" />
<property name="name" column="c_name"/>
</class>
Step 3:
Create a coulmn name "version" in the CAMPIGN table.
Step 4:
In the code
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();
You can handle StaleObjectStateException() and do what ever you want. You can display error message.
Hibernate autumatically create/update the version number when you update/insert any row in the table.
14. What is meant by Concurrency Control mechanism? How many types are there? What is the most advisable concurrency control mechanism?
15.Explain about 1st level and 2nd level caches.
16.Explain briefly about Hibernate annotations.
Ans:Hibernate annotations is the newest way to define mappings without a use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development.
If you going to make your application portable to other EJB 3 compliant ORM applications, you must use annotations to represent the mapping information but still if you want greater flexibility then you should go with XML-based mappings.
Example can be viewed at the following site:
http://www.tutorialspoint.com/hibernate/hibernate_annotations.htm
17.Explain SQL vs. HQL.
18.What is lazy loading and how do you achieve that in hibernate?
Ans:Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.
Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.
Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.
19.How do you switch between relational databases without code changes?
20. What is meant by Named SQL Query?
21.What does it mean to be inverse in Hibernate?
22.Explain Optimistic Concurrency Control in Hibernate.
23.What is the purpose of Hibernate interceptors?
Ans:
As you have learnt that in Hibernate, an object will be created and persisted. Once the object has been changed, it must be saved back to the database. This process continues until the next time the object is needed, and it will be loaded from the persistent store.
Thus an object passes through different stages in its life cycle and Interceptor Interface provides methods which can be called at different stages to perform some required tasks. These methods are callbacks from the session to the application, allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. Following is the list of all the methods available within the Interceptor interface:
S.N.Method and Description
1findDirty() ---This method is be called when the flush() method is called on a Session object.
2instantiate()--This method is called when a persisted class is instantiated.
3isUnsaved()--This method is called when an object is passed to the saveOrUpdate() method
4onDelete()--This method is called before an object is deleted.
5onFlushDirty()--This method is called when Hibernate detects that an object is dirty (ie. have been changed) during a flush i.e. update operation.
6onLoad()--This method is called before an object is initialized.
7onSave()--This method is called before an object is saved.
8postFlush()--This method is called after a flush has occurred and an object has been updated in memory. 9preFlush()--This method is called before a flush. Hibernate Interceptor gives us total control over how an object will look to both the application and the database.
How to use Interceptors? To build an interceptor you can either implement Interceptor class directly or extend EmptyInterceptor class.
Example can be viewed in the following site:
http://www.tutorialspoint.com/hibernate/hibernate_interceptors.htm
24.Explain different inheritance mapping models in Hibernate?
Ans: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
25.what is n+1 query problem in hibernate?
26.What are transient,persistent or detached objects?
Ans:After going through the life cycle, the question that comes into mind is that, how does hibernate know whether an object is transient,persistent or detached ?
A range of options are available for that. Hibernate will assume that an instance is unsaved
Transient instance if :
a) The identifier property is null
b) The version property (if exists) is null.
c) You supply an unsaved-value attribute in and the value of the identifier property
matches.
d) You supply Hibernate Interceptor and return Boolean.TRUE from Interceptor.isUnsaved()
after checking the instance in your code.
27.Hibernate Optimistic Locking without using version(or Timestamp)?
The question I would like to address in this post is about Hibernate optimistic locking ? optimistic locking with no special version number or timestamp. While pessimistic locking is an available option in Hibernate to address concurrency control, for most enterprise applications, optimistic locking is the preferred choice. As the Hibernate documentation states:
?The only approach that is consistent with high concurrency and high scalability, is optimistic concurrency control with versioning?
Hibernate can provide optimistic locking via version number or effectivity timestamp. To learn more about either approach, you can see an earlier post of mine, or check out the Hibernate documentation. Optimistic locking via version number or effectivity timestamp is automatically managed by Hibernate. Simply provide the column to hold the version or timestamp, add the optimistic lock characteristics to your Hibernate mapping (via XML or annotations), and Hibernate does the rest.
Optimistic Locking sans Version or Timestamp However, there may be situations whereby adding a version number or timestamp column to your database table is not possible. This might be the case when a legacy database is in place and many applications use the table and cannot or will not be updated to use a new version/timestamp column for optimistic locking. In this case, Hibernate can compare the column values of a table row against the state of the persistent object to check that nothing in a row was modified before updating the row. There are two forms of this state-checking optimistic locking: all-state-check or dirty-state-check.
Optimistic-lock = ?all? When you set the optimistic-lock attribute on the <class> element in the Hibernate mapping file to the value ?all? (as shown on the Vehicle class mapping below), you are informing Hibernate to check that no column in the associated row has changed since the persistent object was retrieved and before updating the row in the database.
1: <hibernate-mapping package="com.intertech.domain">
2: <class name="Vehicle" dynamic-update="true" optimistic-lock="all">
3: <id name="id">
4: <generator />
5: </id>
6: <property name="make" />
7: <property name="model" />
8: <property name="vin" />
9: </class>
10: </hibernate-mapping>
For example, say you used Hibernate to obtain an instance of Vehicle and then updated it?s make as shown by the code below.
1: SessionFactory sf = new Configuration().configure()
2: .buildSessionFactory();
3: Session sess = sf.openSession();
4: Transaction trx = sess.beginTransaction();
5: Vehicle v = (Vehicle) sess.get(Vehicle.class, 1L);
6: v.setMake("Kia");
7: sess.saveOrUpdate(v);
8: trx.commit();
9: sess.close();
Hibernate would actually use all the existing persistent object values (the last known state values) to form the SQL where-clause used in the update call. Note that every column is mentioned in the where-clause of the example, even the old value of the changed property (make in this case). If any other concurrent activity on this row changed the data of the row (or deleted the row), Hibernate would detect this by the fact that the where-clause would fail to match the row (resulting in a StaleObjectStateException.
1: Hibernate:
2: update
3: Vehicle
4: set
5: make='Kia'
6: where
7: id=1
8: and make='Ford'
9: and model='SUV'
10: and vin=12345
Optimistic-lock = ?dirty? As an alternative, you can also allow Hibernate to only use modified or dirty properties in the where-clause of the update. When mapping the persistent class, set the optimistic-lock attribute to a value of ?dirty? (as shown below).
1: <hibernate-mapping package="com.intertech.domain">
2: <class name="Vehicle" dynamic-update="true" optimistic-lock="dirty">
3: <id name="id">
4: <generator />
5: </id>
6: <property name="make" />
7: <property name="model" />
8: <property name="vin" />
9: </class>
10: </hibernate-mapping>
Hibernate now uses only the last known state values of modified persistent object properties to form the SQL where-clause used in the update call. As an example, assume this code is used to update a Vehicle?s make and model state.
1: SessionFactory sf = new Configuration().configure()
2: .buildSessionFactory();
3: Session sess = sf.openSession();
4: Transaction trx = sess.beginTransaction();
5: Vehicle v = (Vehicle) sess.get(Vehicle.class, 1L);
6: v.setMake("Chevy");
7: v.setModel("sedan");
8: sess.saveOrUpdate(v);
9: trx.commit();
10: sess.close();
The update SQL only includes checks of the existing row?s make and model columns ? that is the dirty properties.
1: Hibernate:
2: update
3: Vehicle
4: set
5: make='Chevy',
6: model='sedan'
7: where
8: id=1
9: and make='Kia'
10: and model='SUV'
This alternative allows other concurrent processes to update the same row so long as they do not modify the same columns. For example, another application could be updating the vin number of our vehicle at the same time we are updating the make and model and neither of the applications suffer a concurrency error. The merits of allowing this type of simultaneous update are questionable (at best). From a business perspective, only you can determine if modifications that do not conflict constitute change that should cause a concurrency failure or not. Hibernate provides the options, you must determine whether the technology fits with your definition of protecting against concurrent change issues.
Dynamic-update must be True It should be noted that in both of these non-version/timestamp optimistic locking options, you must enable dynamic-update (set the dynamic-update='?true? attribute) in the class mapping as shown above. This is because Hibernate cannot generate the SQL for these update statements at application startup (it wouldn?t know what to include in the update statement where-clauses until a change is actually made).
Big Limitations of Non-Version/Timestamp Optimistic Locking Regardless of whether you use the optimistic-lock=all or optimistic-lock=dirty strategy, there are some big limitations to Hibernate?s optimistic locking that does not use version numbers or timestamps.
No Detached When you close a session, Hibernate loses its persistence context and ability to track what changes on the objects. Therefore, you cannot use the optimistic-lock=all or optimistic-lock=dirty option unless you retrieve and modify the persistent object in the same session (i.e. persistence context). If you attempt to get a persistent object in one session, detach the object and then update the object in another session, you will actually create a situation of potentially catastrophic last-in-wins updates. For example, try this code with optimistic-lock set to ?all? on the Vehicle class mapping.
1: SessionFactory sf = new Configuration().configure()
2: .buildSessionFactory();
3: Session sess = sf.openSession();
4: Transaction trx = sess.beginTransaction();
5: Vehicle v = (Vehicle) sess.get(Vehicle.class, 1L);
6: trx.commit();
7: sess.close();
8: System.out.println("vehicle now detached: " + v);
9:
10: v.setVin(7890);
11:
12: //reattach and update
13: sess = sf.openSession();
14: trx = sess.beginTransaction();
15: sess.saveOrUpdate(v);
16: trx.commit();
17: sess.close();
18: System.out.println("vehicle saved again: " + v);
When Hibernate reattaches the Vehicle object and brings it back into the persistence context in the second session, it actually does the unthinkable ? it synchronizes (i.e. updates) every column of the associated row without checking to see if it was updated by some other concurrent process! Last in wins and no concurrency check!!!
1: Hibernate:
2: update
3: Vehicle
4: set
5: make='Chevy',
6: model='sedan',
7: vin=7890
8: where
9: id=1
Not JPA Standard Wonder why I haven?t shown you the annotation form of this non-version optimistic locking yet? If you are currently using annotations to provide all of your object-database mappings, you will also be disappointed to learn JPA does not support optimistic locking outside of versioning (by number or timestamp). So there are no JPA annotations to perform optimistic locking by field or dirty fields. There is, however, a Hibernate annotations that can be used. When mapping, add a parameter to the org.hibernate.annotations.Entity annotation to specify how to perform optimistic locking (as shown here).
1: @Entity
2: @org.hibernate.annotations.Entity(dynamicUpdate = true,
3: optimisticLock = OptimisticLockType.ALL)
4: public class Vehicle {
5: // ...
6: }
Of course, this annotation requires a Hibernate import and more tightly couples your domain class to Hibernate.
It?s Slower Additionally, note that using all-column or dirty-column checks as part of the where-clause is a little slower. When updating a single persistent object every so often, the speed may not be an issue. But in systems dealing with large numbers of transactions, every millisecond counts.
Wrap Up As you can see, Hibernate can perform some real time and code-saving work when it comes to optimistic locking. The several options allow for you to pick a concurrent strategy in-line with your system architecture and business needs. But under most circumstances, Hibernate optimistic locking without a version or timestamp will not work for highly concurrent, highly scalable applications ? and doesn?t that pretty much describe most enterprise application needs today? If you need more help on Hibernate, contact Intertech and consider taking our Complete Hibernate class.
28.What are the different fetching strategy in Hibernate?
Ans:
Hibernate3 defines the following fetching strategies:
29.What are different types of cache hibernate supports ?
Ans:
30.What are the different caching strategies?
Ans:
31.What is the difference between the session.update() method and the session.lock() method?
Ans: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.
32.How would you reatach detached objects to a session when the same object has already been loaded into the session?
Ans: You can use the session.merge() method call.
33.What are the general considerations or best practices for defining your Hibernate persistent classes?
Ans:
34.What is the difference between sorted and ordered collection in hibernate?
Ans:A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.
35.What type of transaction management is supported in hibernate?
Ans:Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions.
non-managed in web containers:
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager" > <property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
managed in application server using JTA:
<bean id="transactionManager" class="org.springframework.transacion.jta.JtaTransactionManager".>
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
Ans: 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
- No SQL to write
- Less java code to write
- Sophisticated caching
- Lazy loading
- Eager loading
A lot less code to write
Improved portability
ORM framework generates database-specific SQL for you
2.What Does Hibernate Simplify?
Ans: 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
3. What’s the difference between load() and get()?
Ans: load() vs. get() :-
load() get()
Only use the load() method if you are sure If you are not sure that the object exists, then use one that the object exists. of the get() methods.
load() method will throw an exception if get() method will return null if the unique id is not the unique id is not found in the database. found in the database.
load() just returns a proxy by default and get() will hit the database immediately.
database won’t be hit until the proxy is first
invoked.
4. What is the difference between and merge and update ?
Ans: 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.
5. Define cascade and inverse option in one-many mapping?
Ans: 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?
6. What is lazy Initializing?
7.What does it mean to be inverse?
Ans: 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.
8. Explain Criteria API
Ans: Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.
Example : List employees = session.createCriteria(Employee.class)
.add(Restrictions.like("name", "a%") )
.add(Restrictions.like("address", "Boston"))
.addOrder(Order.asc("name") )
.list();
9.What are the differences between EJB 3.0 & Hibernate
Ans:
Hibernate Vs EJB 3.0 :-
Hibernate EJB 3.0
Session–Cache or collection of loaded objects Persistence Context-Set of entities that can be relating to a single unit of work managed by a given EntityManager is defined by a persistence unit
XDoclet Annotations used to support Attribute Java 5.0 Annotations used to support Attribute Oriented Programming Oriented Programming
Defines HQL for expressing queries to the Defines EJB QL for expressing queries
database
Supports Entity Relationships through mapping Support Entity Relationships through Java 5.0 files and annotations in JavaDoc annotations
Provides a Persistence Manager API exposed Provides and Entity Manager Interface for
via the Session, Query, Criteria, and managing CRUD operations for an Entity
Transaction API
Provides callback support through lifecycle, Provides callback support through Entity Listener and interceptor, and validatable interfaces Callback methods
Entity Relationships are unidirectional. Entity Relationships are bidirectional or Bidirectional relationships are implemented by unidirectional
two unidirectional relationships
10. What is Lazy Initializing? When do you receive an LazyInitialization Exception?
11. Filter in Hibernate with Example?
Ans:
USER ( ID INT, USERNAME VARCHAR, ACTIVATED BOOLEAN) - TABLE
public class User
{
private int id;
private String username;
private boolean activated;
public boolean isActivated()
{
return activated;
}
public void setActivated(boolean activated)
{
this.activated = activated;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
}
-----------------------------------------------------------------
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User">
<id name="id" >
<generator />
</id>
<property name="username" length="32"/>
<property name="activated" />
<filter name="activatedFilter" condition=":activatedParam = activated"/>
</class>
<filter-def name="activatedFilter">
<filter-param name="activatedParam" />
</filter-def>
</hibernate-mapping>
--------------------------------------------------------------------
Save and Fetch using filter example
User user1 = new User();
user1.setUsername("name1");
user1.setActivated(false);
session.save(user1);
User user2 = new User();
user2.setUsername("name2");
user2.setActivated(true);
session.save(user2);
User user3 = new User();
user3.setUsername("name3");
user3.setActivated(true);
session.save(user3);
User user4 = new User();
user4.setUsername("name4");
user4.setActivated(false);
session.save(user4);
All the four user saved to Data Base User Table.
Now Fetch the User using Filter..
Filter filter = session.enableFilter("activatedFilter");
filter.setParameter("activatedParam",new Boolean(true));
Query query = session.createQuery("from User");
Iterator results = query.iterate();
while (results.hasNext())
{
User user = (User) results.next();
System.out.print(user.getUsername() + " is ");
}
Guess the Result :
name2
name3
Because Filer is filtering ( only true value) data before query execute.
12. EhCache is used for 2nd level cache to store all the redefind data like country table ..
Ans:
When you are creating SessionFactory just add the below steps
String ecache = appHome+File.separatorChar+"ehcache.xml";
try {
CacheManager.create(ecache);
} catch (CacheException e) {
// logger.logError(e);
}*/
Then
sessionFactory = configuration.buildSessionFactory();
ECache.xml is like
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
<cache name="bean.ApplicationBean"
maxElementsInMemory="300"
eternal="false"
overflowToDisk="false"
/>
</ehcache>
ApplicationBean will be avilable in 2nd level cache.
13. How to handle user think time using hibernate ?
Ans: version checking used in hibernate when more then one thread trying to access same data.
For example :
User A edit the row of the TABLE for update ( In the User Interface changing data - This is user thinking time)
and in the same time User B edit the same record for update and click the update. Then User A click the Update and update done. Chnage made by user B is gone. In hibernate you can perevent slate object updatation using version checking. Check the version of the row when you are upding the row. Get the version of the row when you are fetching the row of the TABLE for update. On the time of updation just fetch the version number and match with your version number ( on the time of fetching). This way you can prevent slate object updatation.
Step 1:
Declare a variable "versionId" in your Class with setter and getter.
public class Campign {
private Long versionId;
private Long campignId;
private String name;
public Long getVersionId() {
return versionId;
}
public void setVersionId(Long versionId) {
this.versionId = versionId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getCampignId() {
return campignId;
}
private void setCampignId(Long campignId) {
this.campignId = campignId;
}
}
Step 2:
In the .hbm.xml file
<class name="beans.Campign" table="CAMPIGN" optimistic-lock="version">
<id name="campignId" column="cid">
<generator >
<param name="sequence">CAMPIGN_ID_SEQ</param>
</generator>
</id>
<version name="versionId" column="version" />
<property name="name" column="c_name"/>
</class>
Step 3:
Create a coulmn name "version" in the CAMPIGN table.
Step 4:
In the code
// foo is an instance loaded by a previous Session
session = sf.openSession();
int oldVersion = foo.getVersion();
session.load( foo, foo.getKey() );
if ( oldVersion!=foo.getVersion ) throw new StaleObjectStateException();
foo.setProperty("bar");
session.flush();
session.connection().commit();
session.close();
You can handle StaleObjectStateException() and do what ever you want. You can display error message.
Hibernate autumatically create/update the version number when you update/insert any row in the table.
14. What is meant by Concurrency Control mechanism? How many types are there? What is the most advisable concurrency control mechanism?
15.Explain about 1st level and 2nd level caches.
16.Explain briefly about Hibernate annotations.
Ans:Hibernate annotations is the newest way to define mappings without a use of XML file. You can use annotations in addition to or as a replacement of XML mapping metadata. Hibernate Annotations is the powerful way to provide the metadata for the Object and Relational Table mapping. All the metadata is clubbed into the POJO java file along with the code this helps the user to understand the table structure and POJO simultaneously during the development.
If you going to make your application portable to other EJB 3 compliant ORM applications, you must use annotations to represent the mapping information but still if you want greater flexibility then you should go with XML-based mappings.
Example can be viewed at the following site:
http://www.tutorialspoint.com/hibernate/hibernate_annotations.htm
17.Explain SQL vs. HQL.
18.What is lazy loading and how do you achieve that in hibernate?
Ans:Lazy setting decides whether to load child objects while loading the Parent Object. You need to specify parent class.Lazy = true in hibernate mapping file. By default the lazy loading of the child objects is true. This make sure that the child objects are not loaded unless they are explicitly invoked in the application by calling getChild() method on parent. In this case hibernate issues a fresh database call to load the child when getChild() is actully called on the Parent object. But in some cases you do need to load the child objects when parent is loaded. Just make the lazy=false and hibernate will load the child when parent is loaded from the database.
Examples: Address child of User class can be made lazy if it is not required frequently. But you may need to load the Author object for Book parent whenever you deal with the book for online bookshop.
Hibernate does not support lazy initialization for detached objects. Access to a lazy association outside of the context of an open Hibernate session will result in an exception.
19.How do you switch between relational databases without code changes?
20. What is meant by Named SQL Query?
21.What does it mean to be inverse in Hibernate?
22.Explain Optimistic Concurrency Control in Hibernate.
23.What is the purpose of Hibernate interceptors?
Ans:
As you have learnt that in Hibernate, an object will be created and persisted. Once the object has been changed, it must be saved back to the database. This process continues until the next time the object is needed, and it will be loaded from the persistent store.
Thus an object passes through different stages in its life cycle and Interceptor Interface provides methods which can be called at different stages to perform some required tasks. These methods are callbacks from the session to the application, allowing the application to inspect and/or manipulate properties of a persistent object before it is saved, updated, deleted or loaded. Following is the list of all the methods available within the Interceptor interface:
S.N.Method and Description
1findDirty() ---This method is be called when the flush() method is called on a Session object.
2instantiate()--This method is called when a persisted class is instantiated.
3isUnsaved()--This method is called when an object is passed to the saveOrUpdate() method
4onDelete()--This method is called before an object is deleted.
5onFlushDirty()--This method is called when Hibernate detects that an object is dirty (ie. have been changed) during a flush i.e. update operation.
6onLoad()--This method is called before an object is initialized.
7onSave()--This method is called before an object is saved.
8postFlush()--This method is called after a flush has occurred and an object has been updated in memory. 9preFlush()--This method is called before a flush. Hibernate Interceptor gives us total control over how an object will look to both the application and the database.
How to use Interceptors? To build an interceptor you can either implement Interceptor class directly or extend EmptyInterceptor class.
Example can be viewed in the following site:
http://www.tutorialspoint.com/hibernate/hibernate_interceptors.htm
24.Explain different inheritance mapping models in Hibernate?
Ans: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
25.what is n+1 query problem in hibernate?
26.What are transient,persistent or detached objects?
Ans:After going through the life cycle, the question that comes into mind is that, how does hibernate know whether an object is transient,persistent or detached ?
A range of options are available for that. Hibernate will assume that an instance is unsaved
Transient instance if :
a) The identifier property is null
b) The version property (if exists) is null.
c) You supply an unsaved-value attribute in and the value of the identifier property
matches.
d) You supply Hibernate Interceptor and return Boolean.TRUE from Interceptor.isUnsaved()
after checking the instance in your code.
27.Hibernate Optimistic Locking without using version(or Timestamp)?
The question I would like to address in this post is about Hibernate optimistic locking ? optimistic locking with no special version number or timestamp. While pessimistic locking is an available option in Hibernate to address concurrency control, for most enterprise applications, optimistic locking is the preferred choice. As the Hibernate documentation states:
?The only approach that is consistent with high concurrency and high scalability, is optimistic concurrency control with versioning?
Hibernate can provide optimistic locking via version number or effectivity timestamp. To learn more about either approach, you can see an earlier post of mine, or check out the Hibernate documentation. Optimistic locking via version number or effectivity timestamp is automatically managed by Hibernate. Simply provide the column to hold the version or timestamp, add the optimistic lock characteristics to your Hibernate mapping (via XML or annotations), and Hibernate does the rest.
Optimistic Locking sans Version or Timestamp However, there may be situations whereby adding a version number or timestamp column to your database table is not possible. This might be the case when a legacy database is in place and many applications use the table and cannot or will not be updated to use a new version/timestamp column for optimistic locking. In this case, Hibernate can compare the column values of a table row against the state of the persistent object to check that nothing in a row was modified before updating the row. There are two forms of this state-checking optimistic locking: all-state-check or dirty-state-check.
Optimistic-lock = ?all? When you set the optimistic-lock attribute on the <class> element in the Hibernate mapping file to the value ?all? (as shown on the Vehicle class mapping below), you are informing Hibernate to check that no column in the associated row has changed since the persistent object was retrieved and before updating the row in the database.
1: <hibernate-mapping package="com.intertech.domain">
2: <class name="Vehicle" dynamic-update="true" optimistic-lock="all">
3: <id name="id">
4: <generator />
5: </id>
6: <property name="make" />
7: <property name="model" />
8: <property name="vin" />
9: </class>
10: </hibernate-mapping>
For example, say you used Hibernate to obtain an instance of Vehicle and then updated it?s make as shown by the code below.
1: SessionFactory sf = new Configuration().configure()
2: .buildSessionFactory();
3: Session sess = sf.openSession();
4: Transaction trx = sess.beginTransaction();
5: Vehicle v = (Vehicle) sess.get(Vehicle.class, 1L);
6: v.setMake("Kia");
7: sess.saveOrUpdate(v);
8: trx.commit();
9: sess.close();
Hibernate would actually use all the existing persistent object values (the last known state values) to form the SQL where-clause used in the update call. Note that every column is mentioned in the where-clause of the example, even the old value of the changed property (make in this case). If any other concurrent activity on this row changed the data of the row (or deleted the row), Hibernate would detect this by the fact that the where-clause would fail to match the row (resulting in a StaleObjectStateException.
1: Hibernate:
2: update
3: Vehicle
4: set
5: make='Kia'
6: where
7: id=1
8: and make='Ford'
9: and model='SUV'
10: and vin=12345
Optimistic-lock = ?dirty? As an alternative, you can also allow Hibernate to only use modified or dirty properties in the where-clause of the update. When mapping the persistent class, set the optimistic-lock attribute to a value of ?dirty? (as shown below).
1: <hibernate-mapping package="com.intertech.domain">
2: <class name="Vehicle" dynamic-update="true" optimistic-lock="dirty">
3: <id name="id">
4: <generator />
5: </id>
6: <property name="make" />
7: <property name="model" />
8: <property name="vin" />
9: </class>
10: </hibernate-mapping>
Hibernate now uses only the last known state values of modified persistent object properties to form the SQL where-clause used in the update call. As an example, assume this code is used to update a Vehicle?s make and model state.
1: SessionFactory sf = new Configuration().configure()
2: .buildSessionFactory();
3: Session sess = sf.openSession();
4: Transaction trx = sess.beginTransaction();
5: Vehicle v = (Vehicle) sess.get(Vehicle.class, 1L);
6: v.setMake("Chevy");
7: v.setModel("sedan");
8: sess.saveOrUpdate(v);
9: trx.commit();
10: sess.close();
The update SQL only includes checks of the existing row?s make and model columns ? that is the dirty properties.
1: Hibernate:
2: update
3: Vehicle
4: set
5: make='Chevy',
6: model='sedan'
7: where
8: id=1
9: and make='Kia'
10: and model='SUV'
This alternative allows other concurrent processes to update the same row so long as they do not modify the same columns. For example, another application could be updating the vin number of our vehicle at the same time we are updating the make and model and neither of the applications suffer a concurrency error. The merits of allowing this type of simultaneous update are questionable (at best). From a business perspective, only you can determine if modifications that do not conflict constitute change that should cause a concurrency failure or not. Hibernate provides the options, you must determine whether the technology fits with your definition of protecting against concurrent change issues.
Dynamic-update must be True It should be noted that in both of these non-version/timestamp optimistic locking options, you must enable dynamic-update (set the dynamic-update='?true? attribute) in the class mapping as shown above. This is because Hibernate cannot generate the SQL for these update statements at application startup (it wouldn?t know what to include in the update statement where-clauses until a change is actually made).
Big Limitations of Non-Version/Timestamp Optimistic Locking Regardless of whether you use the optimistic-lock=all or optimistic-lock=dirty strategy, there are some big limitations to Hibernate?s optimistic locking that does not use version numbers or timestamps.
No Detached When you close a session, Hibernate loses its persistence context and ability to track what changes on the objects. Therefore, you cannot use the optimistic-lock=all or optimistic-lock=dirty option unless you retrieve and modify the persistent object in the same session (i.e. persistence context). If you attempt to get a persistent object in one session, detach the object and then update the object in another session, you will actually create a situation of potentially catastrophic last-in-wins updates. For example, try this code with optimistic-lock set to ?all? on the Vehicle class mapping.
1: SessionFactory sf = new Configuration().configure()
2: .buildSessionFactory();
3: Session sess = sf.openSession();
4: Transaction trx = sess.beginTransaction();
5: Vehicle v = (Vehicle) sess.get(Vehicle.class, 1L);
6: trx.commit();
7: sess.close();
8: System.out.println("vehicle now detached: " + v);
9:
10: v.setVin(7890);
11:
12: //reattach and update
13: sess = sf.openSession();
14: trx = sess.beginTransaction();
15: sess.saveOrUpdate(v);
16: trx.commit();
17: sess.close();
18: System.out.println("vehicle saved again: " + v);
When Hibernate reattaches the Vehicle object and brings it back into the persistence context in the second session, it actually does the unthinkable ? it synchronizes (i.e. updates) every column of the associated row without checking to see if it was updated by some other concurrent process! Last in wins and no concurrency check!!!
1: Hibernate:
2: update
3: Vehicle
4: set
5: make='Chevy',
6: model='sedan',
7: vin=7890
8: where
9: id=1
Not JPA Standard Wonder why I haven?t shown you the annotation form of this non-version optimistic locking yet? If you are currently using annotations to provide all of your object-database mappings, you will also be disappointed to learn JPA does not support optimistic locking outside of versioning (by number or timestamp). So there are no JPA annotations to perform optimistic locking by field or dirty fields. There is, however, a Hibernate annotations that can be used. When mapping, add a parameter to the org.hibernate.annotations.Entity annotation to specify how to perform optimistic locking (as shown here).
1: @Entity
2: @org.hibernate.annotations.Entity(dynamicUpdate = true,
3: optimisticLock = OptimisticLockType.ALL)
4: public class Vehicle {
5: // ...
6: }
Of course, this annotation requires a Hibernate import and more tightly couples your domain class to Hibernate.
It?s Slower Additionally, note that using all-column or dirty-column checks as part of the where-clause is a little slower. When updating a single persistent object every so often, the speed may not be an issue. But in systems dealing with large numbers of transactions, every millisecond counts.
Wrap Up As you can see, Hibernate can perform some real time and code-saving work when it comes to optimistic locking. The several options allow for you to pick a concurrent strategy in-line with your system architecture and business needs. But under most circumstances, Hibernate optimistic locking without a version or timestamp will not work for highly concurrent, highly scalable applications ? and doesn?t that pretty much describe most enterprise application needs today? If you need more help on Hibernate, contact Intertech and consider taking our Complete Hibernate class.
28.What are the different fetching strategy in Hibernate?
Ans:
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.
29.What are different types of cache hibernate supports ?
Ans:
- Caching is widely used for optimizing database applications. Hibernate uses two different caches for objects:
- First-level cache: First-level cache is associated with the Session object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses this cache mainly to reduce the number of SQL queries it needs to generate within a given transaction. For example, if an object is modified several times within the same transaction, Hibernate will generate only one SQL UPDATE statement at the end of the transaction, containing all the modifications.
- Second-level cache: second-level cache is associated with the Session Factory object. To reduce database traffic, second-level cache keeps loaded objects at the Session Factory level between transactions. These objects are available to the whole application, not just to the user running the query. This way, each time a query returns an object that is already loaded in the cache, one or more database transactions potentially are avoided.
- Query-level cache: In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects. The query cache should always be used in conjunction with the second-level cache. Hibernate supports the following open-source cache implementations out-of-the-box:
- EHCache is a fast, lightweight, and easy-to-use in-process cache. It supports read-only and read/write caching, and memory- and disk-based caching. However, it does not support clustering.
- OSCache is another open-source caching solution. It is part of a larger package, which also provides caching functionalities for JSP pages or arbitrary objects. It is a powerful and flexible package, which, like EHCache, supports read-only and read/write caching, and memory- and disk-based caching. It also provides basic support for clustering via either JavaGroups or JMS.
- SwarmCache is a simple cluster-based caching solution based on JavaGroups. It supports read-only or nonstrict read/write caching (the next section explains this term). This type of cache is appropriate for applications that typically have many more read operations than write operations.
- JBoss TreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
- Commercial Tangosol Coherence cache.
30.What are the different caching strategies?
Ans:
- Read-only: This strategy is useful for data that is read frequently but never updated. This is by far the simplest and best-performing cache strategy.
- Read/write: Read/write caches may be appropriate if your data needs to be updated. They carry more overhead than read-only caches. In non-JTA environments, each transaction should be completed when Session.close() or Session.disconnect() is called.
- Nonstrict read/write: This strategy does not guarantee that two transactions won't simultaneously modify the same data. Therefore, it may be most appropriate for data that is read often but only occasionally modified.
- Transactional: This is a fully transactional cache that may be used only in a JTA environment.
31.What is the difference between the session.update() method and the session.lock() method?
Ans: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.
32.How would you reatach detached objects to a session when the same object has already been loaded into the session?
Ans: You can use the session.merge() method call.
33.What are the general considerations or best practices for defining your Hibernate persistent classes?
Ans:
- 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.
- You should implement the equals() and hashCode() methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.
- It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster.
- The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects.
- Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.
34.What is the difference between sorted and ordered collection in hibernate?
Ans:A sorted collection is sorted in-memory using java comparator, while order collection is ordered at the database level using order by clause.
35.What type of transaction management is supported in hibernate?
Ans:Hibernate communicates with the database via a JDBC Connection; hence it must support both managed and non-managed transactions.
non-managed in web containers:
<bean id="transactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager" > <property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
managed in application server using JTA:
<bean id="transactionManager" class="org.springframework.transacion.jta.JtaTransactionManager".>
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>