Top Banner
2) What is ORM? ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java application in to the tables of a relational database using the metadata that describes the mapping between the objects and the database. It works by transforming the data from one representation to another. 3) What does an ORM solution comprises of? It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes Should have a language or an API for specifying queries that refer to the classes and the properties of classes An ability for specifying mapping metadata It should have a technique for ORM implementation to interact with transactional objects to perform dirty
122
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Hibernate3 q&a

2) What is ORM?

ORM stands for Object/Relational mapping. It is the programmed and translucent perseverance of objects in a Java

application in to the tables of a relational database using the metadata that describes the mapping between the objects and the

database. It works by transforming the data from one representation to another.

3) What does an ORM solution comprises of?

It should have an API for performing basic CRUD (Create, Read, Update, Delete) operations on objects of persistent classes

Should have a language or an API for specifying queries that refer to the classes and the properties of classes

An ability for specifying mapping metadata It should have a technique for ORM implementation to

interact with transactional objects to perform dirty checking, lazy association fetching, and other optimization functions

4) What are the different levels of ORM quality?

There are four levels defined for ORM quality.

i. Pure relationalii. Light object mapping

iii. Medium object mappingiv. Full object mapping

Page 2: Hibernate3 q&a

5) What is a pure relational ORM?

The entire application, including the user interface, is designed around the relational model and SQL-based relational operations.

6) What is a meant by light object mapping?

The entities are represented as classes that are mapped manually to the relational tables. The code is hidden from the business logic using specific design patterns. This approach is successful for applications with a less number of entities, or applications with common, metadata-driven data models. This approach is most known to all.

7) What is a meant by medium object mapping?

The application is designed around an object model. The SQL code is generated at build time. And the associations between objects are supported by the persistence mechanism, and queries are specified using an object-oriented expression language. This is best suited for medium-sized applications with some complex transactions. Used when the mapping exceeds 25 different database products at a time.

8) What is meant by full object mapping?

Full object mapping supports sophisticated object modeling: composition, inheritance, polymorphism and persistence. The persistence layer implements transparent persistence; persistent classes do not inherit any special base class or have to implement a special interface. Efficient fetching strategies and

Page 3: Hibernate3 q&a

caching strategies are implemented transparently to the application.

9) What are the benefits of ORM and Hibernate?

There are many benefits from these. Out of which the following are the most important one.

i. Productivity – Hibernate reduces the burden of developer by providing much of the functionality and let the developer to concentrate on business logic.

ii. Maintainability – As hibernate provides most of the functionality, the LOC for the application will be reduced and it is easy to maintain. By automated object/relational persistence it even reduces the LOC.

iii. Performance – Hand-coded persistence provided greater performance than automated one. But this is not true all the times. But in hibernate, it provides more optimization that works all the time there by increasing the performance. If it is automated persistence then it still increases the performance.

iv. Vendor independence – Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

10) How does hibernate code looks like?

Session session = getSessionFactory().openSession();

Transaction tx = session.beginTransaction();

Page 4: Hibernate3 q&a

MyPersistanceClass mpc = new MyPersistanceClass ("Sample App");

session.save(mpc);tx.commit();session.close();

The Session and Transaction are the interfaces provided by hibernate. There are many other interfaces besides this.

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

Page 5: Hibernate3 q&a

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 Hibernates concept of a single datastore and is threadsafe so that many threads can access it concurrently and request for sessions and immutable cache of compiled mappings for a single database. A SessionFactory is usually only built once at startup. SessionFactory should be wrapped in some kind of singleton so that it can be easily accessed in an application code.

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-

Page 6: Hibernate3 q&a

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?

Page 7: Hibernate3 q&a

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

Page 8: Hibernate3 q&a

(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

Page 9: Hibernate3 q&a

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()

Page 10: Hibernate3 q&a

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.

)What is Hibernate?

2)What is ORM?

3)What does an ORM solution comprises of?

4)What are the different levels of ORM quality?

5)What is a pure relational ORM?

6)What is a meant by light object mapping?

Page 11: Hibernate3 q&a

7)What is a meant by medium object mapping?

8)What is meant by full object mapping?

9)What are the benefits of ORM and Hibernate?

10)How does hibernate code looks like?

11)What is a hibernate xml mapping document and how does it look like?

12)Show Hibernate overview?

13)What the Core interfaces are of hibernate framework?

14)What are Callback interfaces?

15)What are Extension interfaces?

16)What are the Extension interfaces that are there in hibernate?

17)What are different environments to configure hibernate?

18)What is the file extension you use for hibernate mapping file?

19)What do you create a SessionFactory?

20)What is meant by Method chaining?

21)What does hibernate.properties file consist of?

22)What should SessionFactory be placed so that it can be easily accessed?

Page 12: Hibernate3 q&a

23)What are POJOs?

24)What is object/relational mapping metadata?

25)What is HQL?

26)What are the different types of property and class mappings?

27)What is Attribute Oriented Programming?

28)What are the different methods of identifying an object?

29)What are the different approaches to represent an inheritance hierarchy?

30)What are managed associations and hibernate associations?

Question :If you want to react programmatically while executing methods of Hibernate sessioninstance, what are various ways to accomplish this while using Hibernate?

Answer :By using Hibernate Event system and/or Hibernate Interceptors provided by Hibernate API, one can provide customized handlers and listeners for reactingprogrammatically to the execution of various methods from Hibernate session

Page 13: Hibernate3 q&a

instance.

Question :What will happen if there is a instance level variable defined within eventlistener code?

Answer :As instance of Listener class file are shared across multiple requests, so it is not alright to use instance level variable within Listener class file,as far as thread-safe behavior is concerned, and unless the variable value isto be used in multiple request perspective.

Hibernate Interview Questions 1:

Does Hibernate Session Object has any cache associated with it by default ?

Hibernate Interview

Yes, first-level caching is a mandatory requirement for Hibernate Session Object.

Page 14: Hibernate3 q&a

Answer 1:

Hibernate Interview Questions 2:

Is there any cache associated with Hibernate SessionFactory Object?

Hibernate Interview Answer 2:

Yes, there is an optional second-level cache with Hibernate SessionFactoryobject.

Hibernate Interview Questions 3:

Can a single Hibernate Session object be used across multiple threadsrunning within a process

Hibernate Interview Answer 3:

No, Hibernate Session is basically single-threaded and not to be used acrossmultiple threads.

Hibernat Is this same for Hibernate

Page 15: Hibernate3 q&a

e Interview Questions 4:

SessionFactory object as well?

Hibernate Interview Answer 4:

No, Hibernate SessionFactory is basically thread-safe, thus can be re-usedacross multiple threads and multiple Transacions as well.

Hibernate Interview Questions 5:

How can the second-level caching for Hibernate SessionFactory object bedisabled?

Hibernate Interview Answer 5:

By setting appropriate hibernate.cache configuration related properties, onecan enable/disable second-level caching for Hibernate SessionFactory objectbut only for once before SessionFactory is created

Hibernate Interview

Is it possible to use Hibernate Session object with the scope and contextdefined by JTA Transaction ?

Page 16: Hibernate3 q&a

Questions 6:

Hibernate Interview Answer 6:

Yes, starting with Hibernate 3.0.1 version, Sessionfactory.getCurrentSession methodhas the scope and context defined by the running JTA Transaction scope and context.But as of Hibernate 3.1 version, getCurrentSession method of HibernateSessionFactory has the current Session Scope and Context controlled by pluggablecurrent Session Context class, defined in configuration parameter such ashibernate.current_session_context_class.

Hibernate Interview Questions 7:

As of Hibernate 3.1 version can you be able to explain how many waysscope and context of Hibernate current contextual session be handled?

Hibernate Interview

As of Hibernate 3.1 version, Hibernate has three ways to handle current contextual

Page 17: Hibernate3 q&a

Answer 7:

session, such asJTASessionContextThreadLocalSessionContextManagedSessionContext.

Hibernate Interview Questions 1 :What is the difference between class tag and component tag in Hibernatefrom the persistence perspective?

Hibernate Interview answer 1 :class tag refers to an Entity that is persisted with an identifier, while component tag means the POJO associated with component tag ispersisted along with contained object as a value type.So it doesn't requirean identifier, while the contained object has an entity reference, not for the component object.

Hibernate Interview Questions 2 :What is the difference between component and dynamic component?

Hibernate Interview answer 2 :Component in Hibernate world, means something that is embeded ina contained object and there exist a composition style of binding between

Page 18: Hibernate3 q&a

the contained object and the component object. So component is declaredinside a class tag, just to say one type of use.Dynamic-component has the same characteristics as component but there existsa difference in the way dynamic-component can be used to map a bean's attribute, this can be of type java.util.Map with the key defined in mapping fileand corresponding value from the table's column.So with dynamic-component, there can be possibility of changing the attributekey/value pair during deployment time, just by changing the name and column values in the mapping configuration file.

Hibernate Interview Question :What are the different types of Modes are available, those can beused along with Hibernate Session?

Hibernate Interview Answer :Various Modes like CacheMode, LockMode, EntityMode, FlushMode, ScrollMode, these modes can be used along with Hibernate Session.

Page 19: Hibernate3 q&a

Hibernate Interview Question :What are the various CacheMode available in Hibernate Version 3.2?

Hibernate Interview Answer :Various CacheMode like GET, IGNORE, NORMAL, PUT, REFRESH areavailable with Hibernate's second-level cache.

Hibernate Interview Question :Is there any way not to use Hibernate's second-level cache, whileusing operations of Hibernate Session?

Hibernate Interview Answer:By setting CacheMode.IGNORE as the cache mode for any HibernateSession instance, before any operation on that session is carriedout. This way one can ignore Hibernate's second-level cache whileusing operations of Session.

Hibernate Interview Question :How to disable Hibernate's second-level cache from usage?

Hibernate Interview Answer:

Page 20: Hibernate3 q&a

Just by providing cache provider as org.hibernate.cache.NoCacheProvider, one can disable use of Hibernate's second level cache.Another way is by setting use_second_level_cache from hibernate.cacheproperty, as false.Another way is to use CacheMode.IGNORE along with Hibernate's session.

Hibernate Interview Question :What are the various steps to use Hibernate's second-level cache

Hibernate Interview Answer:One has to define the supporting cache provider for any second-levelcache framework to be used, in Hibernate configuration file along withthe configuration for Hibernate's SessionFactory. Then it is required to enable the use_second_level_cache propertyas true or providing appropriate cache mapping at class or collectionmapping related configuration.

Hibernate Interview Question :What are the various types of cache providers support available with

Page 21: Hibernate3 q&a

Hibernate's second-level cache features in api?

Hibernate Interview Answer:Various cache providers like EhCacheProvider, HashtableCacheProvider,JndiBoundTreeCacheProvider, OptimisticTreeCacheProvider, OSCacheProvider , SwarmCacheProvider and TreeCacheProvider etc.

Hibernate Interview Question : If the project requirement to have the second level cache used in transactional context, which cache would you choose out of those Cache Providers?

Answer:

JBoss TreeCache cache provider and cache framework can be a choice, as it can be used in clustered environment with ip multicast replication mode. And this cache can be used along with a transactional context.

Hibernate Interview Question : How about EHCache and OSCache providers from Hibernate version 3.0,

Page 22: Hibernate3 q&a

can these be used in clustered environment, as of this version?

Answer:

No, these cache providers are capable of running in-memory and disk modes, with no cluster way of execution.

Hibernate Interview Question : How can you avoid synchronization of persistent objects with the database, and do not want to retain this object in the first-level cache, when flush method is called on session?

Answer: By using evict method from session, one can remove specific object from first-level cache of session, and thus can avoid automatic synchronization of object with database, when flush method is called on session instance.

Hibernate Interview Question : Can you be able to evict all objects from the session cache? If yes, How?

Answer:

Page 23: Hibernate3 q&a

Yes, it is possible to evict all objects from the session cache by using clear method on session instance.

Hibernate Interview Question : If anyone wants to perform similar activities with Hibernate's second-level cache, is it possible? If yes, how?

Answer:

Yes, evict object(s) with or without criteria can be possible on Hibernate's second-level cache by using methods on Hibernate's SessionFactory, and methods are evict, evictCollection and many more arguments available.

Hibernate Question : What are the different Transaction Factories available with Hibernate?Hibernate Answer :There are three different types of Transaction Factoryavailable withHibenate 3.2 as JDBCTransactionFactory, JTATransactionFactory andCMTTransactionFactory.

Hibernate Question :

Page 24: Hibernate3 q&a

Which one is the default transaction factory in Hibernate 3.2?

Hibernate interview answerJDBCTransactionFactory is the default local transaction factory withHibernate 3.2.

Hibernate interview questionCan Hibernate Session Factory be bound to JNDI?

Hibernate interview answerYes, by configuring in hibernate.cfg file, sessionfactory can be bound to initial context (as defined byproperties hibernate.jndi.url and hibernate.jndi.class).

Hibernate interview questionCan Hibernate be used to callstored procedures and SQLstatements?

Hibernate interview answerYes, there are provision in Hibernate 3.2, for defining

Page 25: Hibernate3 q&a

callable statements and SQL in mapping HBM files.

Hibernate interview questionCan the custom SQL be defined for creation of Java entityobject by loading values from database tables andpopulating Java Object?

Hibernate interview answerYes, Javaentity objects can be loaded with custom SQLqueries and can be defined in HBM file in form ofHQL (Hibernate Query Language).

Hibernate interview questionWhat are the different Fetching Strategies availablewith Hibernate 3.2?

Hibername interview answerThere are four different Fetching standards available inHibernate3.2, as follows: join fetching, select fetching,batch fetching, sub-select fetching.

Hibernate interview question

Page 26: Hibernate3 q&a

What are the different types of statistics available inHibernate 3.2?

Hibernate interview answerDifferent types of statistics like QueryStatistics,CategorizedStatistics, CollectionStatistics, EntityStatisticsetc., available in Hibernate 3.2.

Hibernate interview questionHow can you get a handle on Hibernate Statistics?

Hibernate interview answerIf Hibernate is deployed in a JMX enabled Applicationserver, then Hibernate provided a statistics service,that can be registered as MBean with JMX server and beused to retrieve different types of statistics available.Hibernate statistics can be obtained from sessionfactory as well.

Hibernate interview questionCan Hibernate be used to map persistent entity POJO to

Page 27: Hibernate3 q&a

XML files?

Hibernate interview answerYes, Hibernate can be used to mapp XML file/tags toPOJO entity classes.

Hibernate Question : If there are multiple databases to be used to interact with domain classes, how can session factory be able to manage multiple datasources?

Hibernate Answer : Each datasource will be configured to each session factory, and to use a single database, a session is created to use database. Question : What is lazy initialization in Hibernate?

Answer :When there is an association of one-to-one, orone-to-many, or many-to-many between classes,and on creation of one object, it has to bedecided whether to bring associated objects along

Page 28: Hibernate3 q&a

with this object or not. By setting lazy="true"we instruct Hibernate not to bring the associatedobject/objects during creation of the required object.By setting lazy="false", it is the reverse, this meanswe instruct Hibernate to bring all the associatedobjects also at the time of returning the associatingobject.

Hibernate interview Question : if there any impact on performanceby this attribute lazy ?

Hibernate interview Answer :This is purely a configuration time decision one hasto take to use lazy attribute and its value (true/false)appropriately. As SessionFactory is created once and reused,all the configuration setting in HBM file is read once,and cann't be changed at runtime.

Hibernate Question : What are the different states

Page 29: Hibernate3 q&a

of an instance in Hibernate?

Hibernate Answer :There are three states that exist for any instance of aclass. These are transient, persistent and detached.Those instances that are created but not associated withany session or not saved in database are trasient objects.Those instances that are created and be used in any of themethods like save, saveOrUpdate, update of Session arecalled persistent objects.Those instances that were used in Session methods like save,saveOrUpdate or update to be inserted or updated in databasetable, and then session is flushed and closed, now theseobjects are in JVM, but these are not bound to any session.

Hibernate interview questionHow can certain type of logic executed on execution ofCRUD operation of session, without duplicating it across

Page 30: Hibernate3 q&a

many places in code base?

Hibernate interview answerHibernate Interceptors can be used to receive callbackfor certain type of events or operations like save, delete,load, update of session. Session Factory level interceptorand session level interceptor. These Interceptors can beused to have code for certain type of logic to be calledfor every lifecycle method of session.

Hibernate interview questionHow can multiple threads access session factorysimulteneously to create session instance?

Hibernate interview answersession factory is thread-safe, so it is okay to be usedby many threads to have session from session factory,but I think session is not thread safe and it should beused by one thread at a time, and after use,session has to be flushed and closed.

Page 31: Hibernate3 q&a

Hibernate interview questionHow many ways Hibernate manages concurrency ?

Hibernate interview answerHibernate has different ways of managing concurrency.These are automatic versioning, detached object andextended user sessions.

Hibernate interview questionWhat is the difference between uni-directional andbi-directional associations?

Hibernate interview answeruni-directional association allows object creation fromone direction only. Bi-directional association allowsobject querying from both directions of fetching objectinstances.

A->B, now querying A, can provide information on B aswell, based on lazy parameter, but in case of A<->B,querying either A or B, will have value of B or A as

Page 32: Hibernate3 q&a

well, respectively.

Hibernate interview QuestionWhat are the different contextual session in Hibernate?

Hibernate interview answerThere are three different types of contextual session Hibernateprovides, these are JTA session context, local thread sessioncontext and managed session context. JTA session context isapplicable in case Hibernate session is running in JTA (JavaTransaction API), request thread level session scoped applicablein case of local thread session, and managed session, requiresapplication to open, close and flush session, so creation ofsession should be handled by application only.

Hibernate interview QuestionCan you tell us difference between Hibernate HQL over SQL?

Hibernate interview answerHQL is fully object oriented, with support for object

Page 33: Hibernate3 q&a

inheritence, polymorphism and association, but SQLis more of Relational with structured form of queries.

Hibernate interview QuestionWhat are the different scopes one can introduce while usingInterceptors with Hibernate?

Hibernate interview AnswerProbably, one can use interceptors with hibernate Sessionscoped or SessionFactory scoped contexts, while usingInterceptors with Hibernate.

Hibernate interview QuestionHow many ways client application that uses Hibernate toreact to certain events?

Hibernate interview AnswerProbably, if I am not wrong, two ways one can react/actto certain events generated out of Hibernate Framework.These are either Interceptors or event systems.

Hibernate interview Question

Page 34: Hibernate3 q&a

Can I be able to persist a XML DOM object tree to databaseby defining mapping between XML DOM to database table,without using POJOs?

Hibernate interview AnswerYes, one can use Hibernate mapping to persist XML DOM treehierarchy to database tables.

Hibernate Interview Question :Suppose Hibernate Filters are defined in HBM file for a class,but need is to not use this filter at runtime, Is it possible?

Hibernate Interview Answer :

Hibernate Filters are to be enabled for any instance of Hibernatesession before use. So whenever is it not required, those filterswon't be used.

Hibernate Interview Question :How can the Hibernate Filter be enabled/ disabled for a session?

Hibernate Interview answer :

Page 35: Hibernate3 q&a

session.enableFilter(method parameters/arguments) is the method forenabling/disabling filter for Hibernate Session instance.

Hibernate Interview Question : In case of a requirement as to use combination of fields from differentclass files those are mapped to different tables. Or in short the requirementis to have functionality of a view (database perspective) but not create a view in database.

Hibernate Interview answer :Yes, using Hibernate Filters one can define certain filter conditions indifferent class file mapping so as to filter the final query result as per the mapping and filter definition.

Hibernate Interview Question :What are the various persistent objects fetching strategies defined in Hibernate3 ?

Hibernate Interview Answer :

There are four different types of persistent objects fetching strategies

Page 36: Hibernate3 q&a

defined in Hibernate3, such as Joing fetching, select fetching, Sub-select fetching and Batch fetching strategies.

Hibernate Interview Question :Can these fetching strategies for retrieving persistent objects, those aredefined in Object Relational Mapping in configuration, be able to over-ridden ?

Hibernate Interview answer :

Yes, fetching strategies as defined in Mapping configuration files can beover-ridden by using HQL or Criteria defined/used with Hibernate Sessioninstance.

Hibernate Interview Question :Can the property tag definition of the class tag for the POJO class that is beingused in O/R Mapping, be lazily loaded by using lazy="true"?

Hibernate Interview Answer :Yes, we can define lazy="true" for any property within a class tag from the O/R mapping file. But we must have to apply proper instrumentation of the build-time

Page 37: Hibernate3 q&a

bytecode of the class that is being used, or else this lazy definition will be ignoredwhile fetching respective persistent object.

Hibernate Interview Question :While working with large binary stream or serializable object to be used with databaseusing Hibernate Session, is there any setting that is to be used in Hibernate specificconfiguration file?

Hibernate Interview Answer :Yes, hibernate.jdbc.use_streams_for_binary setting can be used with value true or false,in case you want to use large binary or serializable data to/from database.

Hibernate Interview Question :While using outer join fetch strategy, can you impose certain depth or level of objecthierarchy to be fetched?

Hibernate Interview Answer :Yes, one can impose certain depth or level of object hierarchy to be fetched while using

Page 38: Hibernate3 q&a

outer join fetch strategy, by using the configuration setting as hibernate.max_fetch_depthwith some count number.

Hibernate Interview Question :In case of highly concurrent database usage mode, can you set for all updates on table tobe executed based on primary key column of the table, for which column data to be updated?

Hibernate Interview Answer :Yes, by using hibernate.order_updates as true or false for achieving/forcing this type of updates based on primary key column values.

Hibernate Interview Question :Suppose you have encountered a situation whereby cluster aware second level cache is not performing properly or upto desired expectation level while working wiht Hibernate. Is there any setting that you can remember that can help by minimizing number of updates

Page 39: Hibernate3 q&a

or object put calls, thus can help in increasing performance of read from cache in clusterenvironment?

Hibernate Interview Answer :hibernate.cache.use_minimal_puts setting in Hibernate configuration file, with a valueas true or false, would optimize Hibernate second-level cache by minimizing number ofadditions/updations to objects those are being cached, thus minimizing overhead associatedwith number of reads from database.

Hibernate Interview Question :How can you log all seond-level cache related activities while using Hibernate Framework?

Hibernate Interview Answer :By using the Log category "org.hibernate.cache", one can obtain log related to Hibernate'ssecond-level cache activities.

Hibernate Interview Question :What are the Transaction Strategies available with Hibernate Framework?

Hibernate Interview Answer :

Page 40: Hibernate3 q&a

Various transaction strategies available in Hibernate as such are forJDBC, JTA and CMT with related TransactionFactories.

Hibernate Interview Question :Does Hibernate as of latest version, provide support for use defined Transaction Factories?

Hibernate Interview Answer :Yes, as of latest version of Hibernate Framework, custom/use defined/supplied TransactionFactories can be used, by defining appropriate factory class file for the setting"hibernate.transaction.factory_class."

Disclaim: These materials mentioned as above, are respective Author's own understanding of Hibernate Framework, for details and complete information, please refer to Hibernate web-sitehttp://www.hibernate.org/

Page 41: Hibernate3 q&a

If anything missed out , please let me know attechienjoy at yahoo . com

Hibernate Example on Filter Criteria :

Example on using Filter Criteriausing Hibernate Framework to work with.

Hibernate class heirarchy mapping :

Hibernate Example on mappingclass hierarchy using various waysof persisting into databasetables.

Hibernate one to many mapping Example :

one to many mapping explained using an exampleand Hibernate Framework.

Hibernate one to one mapping Example :

one to one mapping explained using an exampleand Hibernate Framework.

Hibernate Example on composite Primary key :

Example on using Hibernate Frameworkto work with mapping using compositePrimary key.

Hibernate Join Example :

Using Table join explained with an examplewhile using Hibernate Framework.

Page 42: Hibernate3 q&a

Hibernate Property Formula :

Hibernate Example on PropertyTag with ease to do code walk-through

Hibernate Named Query Example :

Named Query markup using an exampleand Hibernate Framework.

Hibernate Transaction on JBoss :

Explaining Transaction using Hibernateon JBoss Application Server.

Hibernate Interview Questions :

Interview Questions on Hibernate with answer.

Hibernate Bag Mapping Example :

class mapping using Bag Tag example using HibernateFramework and a simple to follow steps.

Hibernate Many to Many Mapping Example :

Many to many mapping example using HibernateFramework and a simple to follow steps.

List of Examples on Hibernate :

List of example using Hibernate.

Hibernate Example on Filter :

Example on using Filter using Hibernate Frameworkto work with.

Class Hierarchy Mapping Hibernate Component

Page 43: Hibernate3 q&a

Example :

class hierarchy mapping example using HibernateFramework and a simple to follow steps.

Property :

Hibernate Example on Componentwith source code explained.

Hibernate Interceptor Example :

Example on using Interceptor using Hibernate Frameworkwith source code explained.

Hibernate one to many mapping Example :

one to many mapping explained using an exampleand Hibernate Framework.

Example on persisting Class Hierarchy :

Example on using Hibernate Frameworkto persist Class Hierarchy into database.

Hibernate Insert Update control :

Hibernate Example on controllinginsert and update attributes

1.What is ORM ?

Page 44: Hibernate3 q&a

ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java application to the tables in a relational database.

2.What 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

Page 45: Hibernate3 q&a

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 productivityo High-level object-oriented API o Less Java code to write o No SQL to write

Improved performanceo Sophisticated caching o Lazy loading o Eager loading

Improved maintainabilityo A lot less code to write

Improved portabilityo ORM framework generates database-specific SQL for

you

6.What Does Hibernate Simplify?

Hibernate simplifies:

Saving and retrieving your domain objects

Page 46: Hibernate3 q&a

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)

Page 47: Hibernate3 q&a

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?

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.

People who read this, also read:-

JSF Interview Questions Core Java Questions J2EE Certification Let Spring Manage JSF Beans JDBC Interview Questions

Page 48: Hibernate3 q&a

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?

Page 49: Hibernate3 q&a

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

Page 50: Hibernate3 q&a

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>

16.What’s the difference between load() and get()?

Page 51: Hibernate3 q&a

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.

18.How do you define sequence generated primary key in hibernate?

Page 52: Hibernate3 q&a

Using <generator> tag.Example:-

<id column="USER_ID" name="id" type="java.lang.Long"> <generator class="sequence"> <param name="table">SEQUENCE_NAME</param>  <generator></id>

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 do you mean by Named – SQL query?

Named SQL queries are defined in the mapping xml document and called wherever required.Example:

Page 53: Hibernate3 q&a

<sql-query name = "empdetails">   <return alias="emp" class="com.test.Employee"/>      SELECT emp.EMP_ID AS {emp.empid},                 emp.EMP_ADDRESS AS {emp.address},                 emp.EMP_NAME AS {emp.name}

FROM Employee EMP WHERE emp.NAME LIKE :name</sql-query>

Invoke Named Query :

List people = session.getNamedQuery("empdetails")

.setString("TomBrady", name) .setMaxResults(50) .list();

21.How do you invoke Stored Procedures?

<sql-query name="selectAllEmployees_SP" callable="true"> <return alias="emp" class="employee">  <return-property name="empid" column="EMP_ID"/>       

<return-property name="name" column="EMP_NAME"/>        <return-property name="address"

Page 54: Hibernate3 q&a

column="EMP_ADDRESS"/>    { ? = call selectAllEmployees() } </return></sql-query>

22.Explain Criteria API

Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.Example :

List employees = session.createCriteria(Employee.class)

       .add(Restrictions.like("name", "a%") )

         .add(Restrictions.like("address", "Boston"))

.addOrder(Order.asc("name") ) .list();

23.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.

Page 55: Hibernate3 q&a

24.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.

25.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.

26.If you want to see the Hibernate generated SQL statements on console, what should we do?

In Hibernate configuration file set as follows: <property name="show_sql">true</property>

27.What are derived properties?

Page 56: Hibernate3 q&a

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.

28.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:

People who read this, also read:-

BREW Interview Questions BREW Questions SCWCD Certification AJAX Form Validation Using DWR and Spring Servlets Interview Questions

Page 57: Hibernate3 q&a

29.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

Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.

Page 58: Hibernate3 q&a

running Hibernate, after the data being read from database using java comparator.

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

Hibernate provides transparent persistence and

Page 59: Hibernate3 q&a

database tables and vice versa conversion is to be taken care of by the developer manually with lines of code.

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

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

Page 60: Hibernate3 q&a

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.

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

Page 61: Hibernate3 q&a

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

Page 62: Hibernate3 q&a

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?

Page 63: Hibernate3 q&a

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.

Page 64: Hibernate3 q&a

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.

Page 65: Hibernate3 q&a

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.

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.

People who read this, also read:-

JDBC Interview Questions JDBC Questions Struts Tutorial JSF Integration with Spring Framework JSP Interview Questions

Page 66: Hibernate3 q&a

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

Java 5.0 Annotations used to support Attribute Oriented

Page 67: Hibernate3 q&a

Programming 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:

Page 69: Hibernate3 q&a

1) Adv/Disadvantages of Hibernate: a) Object – Relational mapping

b) The developer doesn’t have to take into account the type of database he is coding for. The type of database can be changed by changing the dialect line in the configuration file.

c) Hibernate has caching.

d) Need to write less complex queries.

e) One has the choice as to how he wants the related objects of the object he wants to be loaded. (Fetching and join strategy)

f) Connection Pooling can be done by editing a few lines in the hibernate-cfg.xml file ..

    c3p0 :- connection pool built in with Hibernate

    

hibernate.connection.driver_class=com.mysql.jdbc.Driverhibernate.connection.url=jdbc:mysql://localhost/hibernatehibernate.connection.username=roothibernate.connection.password= hibernate.dialect=net.sf.hibernate.dialect.MySQLDialecthibernate.show_sql=false

hibernate.c3p0.max_size=1hibernate.c3p0.min_size=0hibernate.c3p0.timeout=5000hibernate.c3p0.max_statements=100hibernate.c3p0.idle

Page 70: Hibernate3 q&a

_test_period=300hibernate.c3p0.acquire_increment=2

Disadvantages:

slower in processing the queries than if the queries are used directlyadding the xml would cause portability problems

**What is Component mapping?

Answers:

* 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

2) Explain Session Factory? 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.

Page 71: Hibernate3 q&a

SessionFactory sessionFactory = new Configuration().configure().buildSessionfactory

3) Explain different type of fetch statements? Fetching strategy is used by hibernate to retrieve associated objects if the Hibernate needs to go through to the association.

There are 4 types of fetching strategies:

fetch = join

Using the same ‘select’ statement the Hibernate will fetch the associated instance/ collection using outer join.

fetch = select

This is the default option. If there are ‘n’ associated objects to the one you requested then there would be ‘n+1 ′select statements executed. If the lazy=true then these would executed only when the association is required.

fetch = subselect

A second select statement would be used to get all the related objects. If the lazy=true then this second select statement would be executed only when the association is called.

fetch=batch

Page 72: Hibernate3 q&a

It is an optimization strategy for fetch=select , where in using a list of primary or foreign keys one would pull out all instances/collection in a single select.

4) Explain lazy loading?

5) Explain object states? Transient

Persistent

Detached:

Detached objects have a representation in database but changes done to the object won’t be reflected to the database. A detached objects can be created by closing the session or by using the evict method of the session on the object. In order to reflect the changes in the object to the database the load,refresh,merge,update or save method on the object in any session.

6) Performance metrics in Hibernate?sessionFactory.getStatistics

7) 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

Page 73: Hibernate3 q&a

the method session.load(..) throws an exception whereas session.get(…) returns null

 

8) Explain caching in Hibernate

Hibernate uses two different caches for objects: first-level cache and second-level cache. First-level cache is associated with the Session object, while second-level cache is associated with the Session Factory 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. This article focuses on second-level cache. 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.

Page 74: Hibernate3 q&a

In addition, you can use a query-level cache if you need to cache actual query results, rather than just persistent objects.

 

Each cache provides different capacities in terms of performance, memory use, and configuration possibilities:

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.

Page 75: Hibernate3 q&a

Another cache implementation worth mentioning is the commercial Tangosol Coherence cache.

 

Caching StrategiesOnce you have chosen your cache implementation, you need to specify your access strategies. The following four caching strategies are available:

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.

9) Proxy pattern in Hibernate:When an object contains another object and the loading is lazy then when the main object is created then it contains only a

Page 76: Hibernate3 q&a

refernce to the object it contains. This reference is the proxy of the object it contains and this pattern is called proxy patters.

10) Interfaces in Hibernate:Configuration,Session,Transaction and SessionFactory

11) Light weight ,Medium Weight and Heavy Weight mapping:There are four levels of Hibernate Quality:

Pure: Stored Procedures

Light: JDBC

Medium:

Heavy:composition,inheritance, polymorphism, persistence by reachability

12) Difference between Hibernate and Ibatis:In Ibatis Results of the SQL queries are mapped to the Objects where as in Hibernate the table is mapped to the object. Ibatis would be faster as it making use of the queries directly and is useful when you personally don’t have much knowledge about the database.

13) What is NHibernate?

Page 77: Hibernate3 q&a

NHibernate is an Object Relational Mapping (ORM) solution for .Net.

 

14)  Integrating Hibernate and Spring

 1) Configure the SessionFactory in the ‘spring.xml’

<util:list id=”abc.MappingResources”> <value>abcde/a.hbm.xml</value> <value>abcde/b.hbm.xml</value> </util:list>

<bean id=”core.commons.adm.SessionFactory” class=”org.springframework.orm.hibernate3.LocalSessionFactoryBean” p:dataSource-ref=”data.source.DataSource” p:mappingResources-ref=”abc.MappingResources” p:hibernateProperties-ref=”abc.HibernateProperties”> <property name=”jtaTransactionManager”> <bean class=”org.springframework.jndi.JndiObjectFactoryBean”> <property name=”jndiName”>

Page 78: Hibernate3 q&a

<value>javax.transaction.TransactionManager</value> </property> </bean> </property> </bean>

2) Configure the DataSource in the ‘spring.xml’

<bean id=“dataSource”class=“org.springframework.jdbc.datasource.DriverManagerDataSource”>

  <property name=“driverClassName”>    <value>org.hsqldb.jdbcDriver</value>  </property>  <property name=“url”>    <value>jdbc:hsqldb:mem:widgets</value>

  </property>  <property name=“username”><value>sa</value></property>  <property name=“password”><value></value></property></bean>

Page 79: Hibernate3 q&a

 

 

Interceptors can be used in cases where we may requiresome sort of callback methods called just before theactual operation is called. For example If it is requiredto log any perticular SQL in some different log/audit file,then we can set a simple Interceptor like CaptureSQL orLogSQL, just while opening Sesson using SessionFactoryopenSession (Interceptor) method.

Following sample interceptor does the logging of SQLon prepare statement.

import org.apache.log4j.Logger;import org.hibernate.EmptyInterceptor;

public class CaptureSQL extends EmptyInterceptor { private static Logger log = Logger.getLogger("L1");

public String onPrepareStatement(String

Page 80: Hibernate3 q&a

sql) {log.debug("Loging SQL

statement ...... start");log.debug(sql);log.debug("Loging SQL

statement ...... end");return sql;

}}

CaptureSQL is the user defined class that extendsorg.hibernate.EmptyInterceptor to become receivingcallback overridden method, such as"onPrepareStatement", when ever a Session is opened,by calling SessionFactory.openSession(new CaptureSQL()).

Appropriate log4j.properties file should be configuredto be able to handle these logging part. My sample log4j.propertiesfile is as follows:

Page 81: Hibernate3 q&a

log4j.rootLogger=DEBUGlog4j.logger.L1=INHERIT, Llog4j.appender.L=org.apache.log4j.FileAppenderlog4j.appender.L.file=sample.txtlog4j.appender.L.layout=org.apache.log4j.PatternLayoutlog4j.appender.L.layout.ConversionPattern=%d [%t] %C{1} - %m%n

And the Client code is as follows:

Client.java (Hibernate one to one mapping Test main class) // This source is provided on "AS IS" basis.import java.util.Calendar;

import org.hibernate.Session;import org.hibernate.SessionFactory;import org.hibernate.Transaction;import org.hibernate.cfg.Configuration;

import org.apache.log4j.Logger;

public class Client {

private static final SessionFactory sessionFactory; static {

Page 82: Hibernate3 q&a

try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }

public static SessionFactory getSessionFactory() { return sessionFactory; } public static void createRecord() {

Session session = getSessionFactory().openSession(new CaptureSQL());

Transaction trx = session.beginTransaction();

trx.begin();Car car = new Car();car.setCarName("My Car1");car.setModel("My Model1");

Page 83: Hibernate3 q&a

car.setSegment("My Segment1"); session.persist(car);

trx.commit();session.close();

} /**

* @param args */public static void main(String[] args)

{

createRecord();}

}

hibernate.cfg.xml (configuration file for creation of Hibernate session factory) // This source is provided on "AS IS" basis.<?xml version='1.0' encoding='utf-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

Page 84: Hibernate3 q&a

<session-factory>

<!-- Database connection settings --> <property name="connection.driver_class">

org.hsqldb.jdbcDriver </property> <property name="connection.url">

jdbc:hsqldb:hsql://localhost/ </property> <property name="connection.username">sa</property> <property name="connection.password"></property>

<!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property>

<!-- SQL dialect --> <property name="dialect">

org.hibernate.dialect.HSQLDialect</property>

<!-- Enable Hibernate's automatic session context management --> <property name="current_session_context_class">

thread

Page 85: Hibernate3 q&a

</property>

<!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property>

<mapping resource="car.hbm.xml"/>

</session-factory>

</hibernate-configuration>

This example domain class "Car.java" file is as follows:

// This source is provided on "AS IS" basis.

public class Car { private String carName; private String model; private String segment;

public String getCarName() {return carName;

} public void setCarName(String carName) {

this.carName = carName; } public String getModel() {

Page 86: Hibernate3 q&a

return model; } public void setModel(String model) {

this.model = model; } public String getSegment() {

return segment; } public void setSegment(String segment) {

this.segment = segment; }}

And the corresponding Hibernate HBM configuration file is as follows:

// This source is provided on "AS IS" basis.<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping> <class name="Car" table="Car"> <id name="carName" access="property" column="car_name"/> <property name="model" column="car_model"/>

Page 87: Hibernate3 q&a

<property name="segment" column="car_segment"/> </class></hibernate-mapping>

In order to execute this example, you may have to create relevant table(the DDL as shown below) or use appropriate configuration entry forcreation of database table at runtime.

// This source is provided on "AS IS" basis.create table car(car_name varchar(20), car_model varchar(50), car_segment varchar(50), primary key (car_name));

On executing Client code, we can see logs are getting writtenonto the sample.txt log file, as shown follows:

2009-01-04 09:01:11,578 [main] CaptureSQL - Loging SQL statement .start2009-01-04 09:01:11,593 [main] CaptureSQL -This is a log statement before onPrepareStatement:

Page 88: Hibernate3 q&a

<<The DML used in this operation on the Session opened withCatureSQL as interceptor>>2009-01-04 09:01:11,593 [main] CaptureSQL - Loging SQL statement .end

There are many other interesting callback methodscan be used from EmptyInterceptor, such as

findDirty -> to check where the Entity in use is dirty or not. -> if this method returns an empty int[] array, then the Entity object supplied in argument of this method is not dirty. -> if this method returns an empty int[] array, then the Entity object is dirty or is updated by some other process in database. -> by returning a null from the overridden findDirty method one can opt for using Hibernate's own or default dirty checking mechanism.

onLoad -> it is called just before Entity object is initialized.

Page 89: Hibernate3 q&a

onDelete -> it is called just before Entity object is deleted.

and many more callback methods as defined inorg.hibernate.Intercept interface.

Hibernate Question on Interceptor 2:Can there be any Interceptor for SessionFactory, so thatit can be used across all the Session from this SessionFactory?

Yes, there can be an Interceptor defined in org.hibernate.cfg.Configuration

to be defined during SessionFactory creation.Configuration.setInterceptor method can be used for this purpose.

Hibernate Question on Interceptor 3:Can one be able to use Hibernate Session from within the callbackmethods of Interceptor?

No, Session may not be used from the callback methods of Interceptor.

Page 90: Hibernate3 q&a

Hibernate Question on Interceptor 4:Can the collection be recreated/initialized lazily while executing anycallback method from Interceptor?

No, Collection may not be lazily initialized, from callback methodof Interceptors.

Interceptors in Hibernate Framework can be of two different scopes,such as session scoped and session factory scoped.

In this example and above code is implemented using Hibernate sesssionscoped interceptors in mind.

In the following section we shall re-create this example using Hibernate session factory scoped interceptor.

Just you have to do is to change the static initializer block in the Clientprogram, and set appropriate interceptor instance into the Configurationinstance, and use this interceptor while building Hibernate session factory.

Page 91: Hibernate3 q&a

And of course you may open session with no interceptor instance passed as constructor argument in the createRecord method.

Code snippet as shown below:

// This source is provided on "AS IS" basis. static { try { // Create the SessionFactory from hibernate.cfg.xml sessionFactory = new Configuration().setInterceptor(new CaptureSQL()).configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log the exception, as it might be swallowed System.err.println("Initial SessionFactory creation failed." + ex); throw new ExceptionInInitializerError(ex); } }

Page 92: Hibernate3 q&a

If you like to share your comment/suggestions/feedback relating to this Page,you can do so by droping us an email at usingframeworks @ gmail . comwith the subject line mentioning URL for this Page (i.e, /Hibernate-Interceptor-example.php) or use thisLINK.As per this website's privacy policy, we never disclose your email id,though we shall post your comments/suggestions/feedback withyour name (optional) and date on this Page. If you don't want yourcomments/suggestions/feedback to be shared in this Page, pleasemention so in your email to us. Thank you very much.....If anything missed out , please let me know attechienjoy at yahoo . com