You are on page 1of 93

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. ii. iii. iv. Pure relational Light object mapping Medium object mapping Full object mapping

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

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. 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. 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. Vendor independence Irrespective of the different types of databases that are there, hibernate provides a much easier way to develop a cross platform application.

ii.

iii.

iv.

10) How does hibernate code looks like? Session session = getSessionFactory().openSession(); Transaction tx = session.beginTransaction();

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

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-

work with the database. Sessions are opened by a SessionFactory and then are closed when all work is complete. Session is the primary interface for the persistence service. A session obtains a database connection lazily (i.e. only when required). To avoid creating too many sessions ThreadLocal class can be used as shown below to get the current session no matter how many times you make call to the currentSession() method. & public class HibernateUtil { & public static final ThreadLocal local = new ThreadLocal(); public static Session currentSession() throws HibernateException { Session session = (Session) local.get(); //open a new session if this thread has no session if(session == null) { session = sessionFactory.openSession(); local.set(session); } return session; } } It is also vital that you close your session after your unit of work completes. Note: Keep your Hibernate Session API handy.

Q. What are the benefits of detached objects?

Answer: Detached objects can be passed across layers all the way up to the presentation layer without having to use any DTOs (Data Transfer Objects). You can later on re-attach the detached objects to another session. Q. What are the pros and cons of detached objects? Answer: Pros: " When long transactions are required due to user think-time, it is the best practice to break the long transaction up into two or more transactions. You can use detached objects from the first transaction to carry data all the way up to the presentation layer. These detached objects get modified outside a transaction and later on re-attached to a new transaction via another session.

Cons " In general, working with detached objects is quite cumbersome, and better to not clutter up the session with them if possible. It is better to discard them and re-fetch them on subsequent requests. This approach is not only more portable but also more efficient because - the objects hang around in Hibernate's cache anyway. " Also from pure rich domain driven design perspective it is recommended to use DTOs (DataTransferObjects) and DOs

(DomainObjects) to maintain the separation between Service and UI tiers.

Q. How does Hibernate distinguish between transient (i.e. newly instantiated) and detached objects? Answer " Hibernate uses the version property, if there is one. " If not uses the identifier value. No identifier value means a new object. This does work only for Hibernate managed surrogate keys. Does not work for natural keys and assigned (i.e. not managed by Hibernate) surrogate keys. " Write your own strategy with Interceptor.isUnsaved().

Q. What is the difference between the session.get() method and the session.load() method? Both the session.get(..) and session.load() methods create a persistent object by loading the required object from the database. But if there was not such object in the database then the method session.load(..) throws an exception whereas session.get(&) returns null.

Q. What is the difference between the session.update() method and the session.lock() method? Both of these methods and saveOrUpdate() method are

intended for reattaching a detached object. The session.lock() method simply reattaches the object to the session without checking or updating the database on the assumption that the database in sync with the detached object. It is the best practice to use either session.update(..) or session.saveOrUpdate(). Use session.lock() only if you are absolutely sure that the detached object is in sync with your detached object or if it does not matter because you will be overwriting all the columns that would have changed later on within the same transaction. Note: When you reattach detached objects you need to make sure that the dependent objects are reatched as well. Q. How would you reatach detached objects to a session when the same object has already been loaded into the session? You can use the session.merge() method call.

Q. What are the general considerations or best practices for defining your Hibernate persistent classes?

1.You must have a default no-argument constructor for your persistent classes and there should be getXXX() (i.e accessor/getter) and setXXX( i.e. mutator/setter) methods for all your persistable instance variables. 2.You should implement the equals() and hashCode()

methods based on your business key and it is important not to use the id field in your equals() and hashCode() definition if the id field is a surrogate key (i.e. Hibernate managed identifier). This is because the Hibernate only generates and sets the field when saving the object.

3. It is recommended to implement the Serializable interface. This is potentially useful if you want to migrate around a multi-processor cluster. 4.The persistent class should not be final because if it is final then lazy loading cannot be used by creating proxy objects. 5.Use XDoclet tags for generating your *.hbm.xml files or Annotations (JDK 1.5 onwards), which are less verbose than *.hbm.xml files.

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

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?

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 session instance, 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 reacting programmatically to the execution of various methods from Hibernate session

instance. Question : What will happen if there is a instance level variable defined within event listener 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 is to be used in multiple request perspective.

Hibernat e Intervie Does Hibernate Session Object has any cache associated with it by w default ? Question s 1: Hibernat Yes, first-level caching is a mandatory requirement for Hibernate

Session Object. e Intervie w Answer 1: Hibernat e Intervie Is there any cache associated with w Hibernate SessionFactory Object? Question s 2: Hibernat e Intervie w Answer 2:

Yes, there is an optional secondlevel cache with Hibernate SessionFactory object.

Hibernat e Can a single Hibernate Session Intervie object be used across multiple w threads Question running within a process s 3:

Hibernat e Intervie w Answer 3:

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

Hibernat e Intervie Is this same for Hibernate w SessionFactory object as well? Question s 4: Hibernat e Intervie w Answer 4:

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

Hibernat How can the second-level caching for e Hibernate SessionFactory object be Intervie disabled? w Question

s 5: Hibernat e Intervie w Answer 5: By setting appropriate hibernate.cache configuration related properties, one can enable/disable second-level caching for Hibernate SessionFactory object but only for once before SessionFactory is created

Hibernat e Is it possible to use Hibernate Intervie Session object with the scope and w context Question defined by JTA Transaction ? s 6: Hibernat e Intervie w Answer 6: Yes, starting with Hibernate 3.0.1 version, Sessionfactory.getCurrentSession method has the scope and context defined by the running JTA Transaction scope and context. But as of Hibernate 3.1 version, getCurrentSession method of Hibernate SessionFactory has the current Session Scope and Context controlled by pluggable

current Session Context class, defined in configuration parameter such as hibernate.current_session_context_cl ass. Hibernat e As of Hibernate 3.1 version can you Intervie be able to explain how many ways scope and context of Hibernate w current contextual session be Question handled? s 7: Hibernat e Intervie w Answer 7: As of Hibernate 3.1 version, Hibernate has three ways to handle current contextual session, such as JTASessionContext ThreadLocalSessionContext ManagedSessionContext.

Hibernate Interview Questions 1 : What is the difference between class tag and component tag in Hibernate from 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 is persisted along with contained object as a value type.So it doesn't require an 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 in a contained object and there exist a composition style of binding between the contained object and the component object. So component is declared inside a class tag, just to say one type of use. Dynamic-component has the same characteristics as component but there exists a 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 file and corresponding value from the table's column.

So with dynamic-component, there can be possibility of changing the attribute key/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 be used along with Hibernate Session? Hibernate Interview Answer : Various Modes like CacheMode, LockMode, EntityMode, FlushMode, ScrollMode, these modes can be used along with Hibernate Session. 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 are available with Hibernate's second-level cache. Hibernate Interview Question :

Is there any way not to use Hibernate's second-level cache, while using operations of Hibernate Session? Hibernate Interview Answer: By setting CacheMode.IGNORE as the cache mode for any Hibernate Session instance, before any operation on that session is carried out. This way one can ignore Hibernate's second-level cache while using operations of Session. Hibernate Interview Question : How to disable Hibernate's second-level cache from usage? Hibernate Interview Answer: 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.cache property, 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-level cache framework to be used, in Hibernate configuration file along with the configuration for Hibernate's SessionFactory. Then it is required to enable the use_second_level_cache property as true or providing appropriate cache mapping at class or collection mapping related configuration. Hibernate Interview Question : What are the various types of cache providers support available with 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, 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: 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 with Hibenate 3.2 as JDBCTransactionFactory, JTATransactionFactory and CMTTransactionFactory. Hibernate Question : Which one is the default transaction factory in Hibernate 3.2? Hibernate interview answer JDBCTransactionFactory is the default local transaction factory withHibernate 3.2.

Hibernate interview question Can Hibernate Session Factory be bound to JNDI? Hibernate interview answer Yes, by configuring in hibernate.cfg file, session factory can be bound to initial context (as defined by properties hibernate.jndi.url and hibernate.jndi.class). Hibernate interview question Can Hibernate be used to call stored procedures and SQL statements? Hibernate interview answer Yes, there are provision in Hibernate 3.2, for defining callable statements and SQL in mapping HBM files. Hibernate interview question Can the custom SQL be defined for creation of Java entity object by loading values from database tables and populating Java Object?

Hibernate interview answer Yes, Javaentity objects can be loaded with custom SQL queries and can be defined in HBM file in form of HQL (Hibernate Query Language). Hibernate interview question What are the different Fetching Strategies available with Hibernate 3.2? Hibername interview answer There are four different Fetching standards available in Hibernate3.2, as follows: join fetching, select fetching, batch fetching, sub-select fetching. Hibernate interview question What are the different types of statistics available in Hibernate 3.2? Hibernate interview answer Different types of statistics like QueryStatistics, CategorizedStatistics, CollectionStatistics, EntityStatistics etc., available in Hibernate 3.2.

Hibernate interview question How can you get a handle on Hibernate Statistics? Hibernate interview answer If Hibernate is deployed in a JMX enabled Application server, then Hibernate provided a statistics service, that can be registered as MBean with JMX server and be used to retrieve different types of statistics available. Hibernate statistics can be obtained from session factory as well. Hibernate interview question Can Hibernate be used to map persistent entity POJO to XML files? Hibernate interview answer Yes, Hibernate can be used to mapp XML file/tags to POJO 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, or one-to-many, or many-to-many between classes, and on creation of one object, it has to be decided whether to bring associated objects along with this object or not. By setting lazy="true" we instruct Hibernate not to bring the associated object/objects during creation of the required object. By setting lazy="false", it is the reverse, this means

we instruct Hibernate to bring all the associated objects also at the time of returning the associating object. Hibernate interview Question : if there any impact on performance by this attribute lazy ? Hibernate interview Answer : This is purely a configuration time decision one has to 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 of an instance in Hibernate? Hibernate Answer : There are three states that exist for any instance of a class. These are transient, persistent and detached.

Those instances that are created but not associated with any session or not saved in database are trasient objects. Those instances that are created and be used in any of the methods like save, saveOrUpdate, update of Session are called persistent objects. Those instances that were used in Session methods like save, saveOrUpdate or update to be inserted or updated in database table, and then session is flushed and closed, now these objects are in JVM, but these are not bound to any session. Hibernate interview question How can certain type of logic executed on execution of CRUD operation of session, without duplicating it across many places in code base? Hibernate interview answer Hibernate Interceptors can be used to receive callback for certain type of events or operations like save, delete,

load, update of session. Session Factory level interceptor and session level interceptor. These Interceptors can be used to have code for certain type of logic to be called for every lifecycle method of session. Hibernate interview question How can multiple threads access session factory simulteneously to create session instance? Hibernate interview answer session factory is thread-safe, so it is okay to be used by many threads to have session from session factory, but I think session is not thread safe and it should be used by one thread at a time, and after use, session has to be flushed and closed. Hibernate interview question How many ways Hibernate manages concurrency ? Hibernate interview answer Hibernate has different ways of managing concurrency.

These are automatic versioning, detached object and extended user sessions. Hibernate interview question What is the difference between unidirectional and bi-directional associations? Hibernate interview answer uni-directional association allows object creation from one direction only. Bi-directional association allows object querying from both directions of fetching object instances. A->B, now querying A, can provide information on B as well, based on lazy parameter, but in case of A<->B, querying either A or B, will have value of B or A as well, respectively. Hibernate interview Question What are the different contextual session in Hibernate? Hibernate interview answer

There are three different types of contextual session Hibernate provides, these are JTA session context, local thread session context and managed session context. JTA session context is applicable in case Hibernate session is running in JTA (Java Transaction API), request thread level session scoped applicable in case of local thread session, and managed session, requires application to open, close and flush session, so creation of session should be handled by application only. Hibernate interview Question Can you tell us difference between Hibernate HQL over SQL? Hibernate interview answer HQL is fully object oriented, with support for object inheritence, polymorphism and association, but SQL is more of Relational with structured form of queries. Hibernate interview Question

What are the different scopes one can introduce while using Interceptors with Hibernate? Hibernate interview Answer Probably, one can use interceptors with hibernate Session scoped or SessionFactory scoped contexts, while using Interceptors with Hibernate. Hibernate interview Question How many ways client application that uses Hibernate to react to certain events? Hibernate interview Answer Probably, if I am not wrong, two ways one can react/act to certain events generated out of Hibernate Framework. These are either Interceptors or event systems. Hibernate interview Question Can I be able to persist a XML DOM object tree to database by defining mapping between XML DOM to database table, without using POJOs?

Hibernate interview Answer Yes, one can use Hibernate mapping to persist XML DOM tree hierarchy 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 Hibernate session before use. So whenever is it not required, those filters won't be used. Hibernate Interview Question : How can the Hibernate Filter be enabled/ disabled for a session? Hibernate Interview answer : session.enableFilter(method parameters/arguments) is the method for enabling/disabling filter for Hibernate Session instance. Hibernate Interview Question :

In case of a requirement as to use combination of fields from different class files those are mapped to different tables. Or in short the requirement is 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 in different 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 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 are

defined in Object Relational Mapping in configuration, be able to over-ridden ? Hibernate Interview answer : Yes, fetching strategies as Mapping configuration files over-ridden by using HQL or defined/used with Hibernate instance. defined in can be Criteria Session

Hibernate Interview Question : Can the property tag definition of the class tag for the POJO class that is being used 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 bytecode of the class that is being used, or else this lazy definition will be ignored while fetching respective persistent object. Hibernate Interview Question :

While working with large binary stream or serializable object to be used with database using Hibernate Session, is there any setting that is to be used in Hibernate specific configuration 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 object hierarchy to be fetched? Hibernate Interview Answer : Yes, one can impose certain depth or level of object hierarchy to be fetched while using outer join fetch strategy, by using the configuration setting as hibernate.max_fetch_depth with some count number. Hibernate Interview Question :

In case of highly concurrent database usage mode, can you set for all updates on table to be 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 or object put calls, thus can help in increasing performance of read from cache in cluster environment? Hibernate Interview Answer : hibernate.cache.use_minimal_puts setting in Hibernate configuration file, with a value

as true or false, would optimize Hibernate second-level cache by minimizing number of additions/updations to objects those are being cached, thus minimizing overhead associated with 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's second-level cache activities. Hibernate Interview Question : What are the Transaction Strategies available with Hibernate Framework? Hibernate Interview Answer : Various transaction strategies available in Hibernate as such are for JDBC, 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 Transaction Factories 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-site http://www.hibernate.org/ If anything missed out , please let me know at techienjoy at yahoo . com

Hibernate Example on Filter

Hibernate class heirarchy

Criteria : Example on using Filter Criteria using Hibernate Framework to work with.

mapping : Hibernate Example on mapping class hierarchy using various ways of persisting into database tables. Hibernate one to one mapping Example : one to one mapping explained using an example and Hibernate Framework. Hibernate Join Example : Using Table join explained with an example while using Hibernate Framework. Hibernate Named Query Example : Named Query markup using an example

Hibernate one to many mapping Example : one to many mapping explained using an example and Hibernate Framework. Hibernate Example on composite Primary key : Example on using Hibernate Framework to work with mapping using composite Primary key. Hibernate Property Formula : Hibernate Example on Property Tag with ease to do

code walk-through Hibernate Transaction on JBoss : Explaining Transaction using Hibernate on JBoss Application Server. Hibernate Bag Mapping Example : class mapping using Bag Tag example using Hibernate Framework and a simple to follow steps. List of Examples on Hibernate :

and Hibernate Framework. Hibernate Interview Questions : Interview Questions on Hibernate with answer. Hibernate Many to Many Mapping Example : Many to many mapping example using Hibernate Framework and a simple to follow steps. Hibernate Example on Filter :

Example on using Filter using List of example using Hibernate Framework Hibernate. to work with. Class Hierarchy Mapping Example : class hierarchy Hibernate Component Property : Hibernate Example on

mapping example using Component Hibernate with source code Framework and a explained. simple to follow steps. Hibernate Interceptor Example : Example on using Interceptor using Hibernate Framework with source code explained. Example on persisting Class Hierarchy : Example on using Hibernate Framework to persist Class Hierarchy into database. Hibernate one to many mapping Example : one to many mapping explained using an example and Hibernate Framework. Hibernate Insert Update control : Hibernate Example on controlling insert and update attributes

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

2.What does ORM consists of ? An ORM solution consists of the followig four pieces:

API for performing basic CRUD operations API to express queries refering to classes Facilities to specify metadata Optimization facilities : dirty checking,lazy associations fetching

3.What are the ORM levels ? The ORM levels are:


Pure relational (stored procedure.) Light objects mapping (JDBC) Medium object mapping Full object Mapping (composition,inheritance, polymorphism, persistence by reachability)

4.What is Hibernate? Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is to relieve the developer from a significant amount of relational data persistence-related programming tasks.

5.Why do you need ORM tools like hibernate? The main advantage of ORM like hibernate is that it shields developers from messy SQL. Apart from this, ORM provides following benefits:

Improved productivity o High-level object-oriented API o Less Java code to write o No SQL to write Improved performance o Sophisticated caching o Lazy loading o Eager loading Improved maintainability o A lot less code to write Improved portability o ORM framework generates database-specific SQL for you

6.What Does Hibernate Simplify? Hibernate simplifies:


Saving and retrieving your domain objects Making database column and table name changes Centralizing pre save and post retrieve logic Complex joins for retrieving related items Schema creation from object model

7.What is the need for Hibernate xml mapping file? Hibernate mapping file tells Hibernate which tables and columns to use to load and store objects. Typical mapping file look as follows:

8.What are the most common methods of Hibernate configuration? The most common methods of Hibernate configuration are:

Programmatic configuration XML configuration (hibernate.cfg.xml)

9.What are the important tags of hibernate.cfg.xml? 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

Session interface SessionFactory interface Configuration interface

Transaction interface Query and Criteria interfaces

11.What role does the Session interface play in Hibernate? The Session interface is the primary interface used by Hibernate applications. It is a single-threaded, short-lived object representing a conversation between the application and the persistent store. It allows you to create query objects to retrieve persistent objects. Session session = sessionFactory.openSession(); Session interface role:

Wraps a JDBC connection Factory for Transaction Holds a mandatory (first-level) cache of persistent objects, used when navigating the object graph or looking up objects by identifier

12.What role does the SessionFactory interface play in Hibernate? The application obtains Session instances from a SessionFactory. There is typically a single SessionFactory for the whole applicationreated during application initialization.

The SessionFactory caches generate SQL statements and other mapping metadata that Hibernate uses at runtime. It also holds cached data that has been read in one unit of work and may be reused in a future unit of work SessionFactory sessionFactory = configuration.buildSessionFactory(); 13.What is the general flow of Hibernate communication with RDBMS? The general flow of Hibernate communication with RDBMS is :

Load the Hibernate configuration file and create configuration object. It will automatically load all hbm mapping files Create session factory from configuration object Get one session from this session factory Create HQL Query Execute query to get list containing Java objects

14.What is Hibernate Query Language (HQL)? Hibernate offers a query language that embodies a very powerful and flexible mechanism to query, store, update, and retrieve objects from a database. This language, the Hibernate query Language (HQL), is an object-oriented extension to SQL.

15.How do you map Java Objects with Database tables?

First we need to write Java domain objects (beans with setter and getter). Write hbm.xml, where we map java class to table and database columns to Java class variables.

Example : <hibernate-mapping> <class name="com.test.User" table="user"> <property column="USER_NAME" length="255" name="userName" not-null="true" type="java.lang.String"/> <property column="USER_PASSWORD" length="255" name="userPassword" not-null="true" type="java.lang.String"/> </class> </hibernate-mapping>

16.Whats the difference between load() and get()? load() vs. get() :-

load()

get()

Only use the load() method if If you are not sure that the object exists, then use one of you are sure that the object the get() methods. exists. load() method will throw an get() method will return exception if the unique id is not null if the unique id is not found in the database. found in the database. load() just returns a proxy by default and database wont be get() will hit the database hit until the proxy is first immediately. invoked.

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?

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:

<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" 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.Hibernate Template is a helper class which provides different methods for querying/retrieving data from the database. It also converts checked HibernateExceptions into unchecked DataAccessExceptions.

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?

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. People who read this, also read:

28.What is component mapping in Hibernate?

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

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:

29.What is the difference between sorted and ordered collection in hibernate? sorted collection vs. order collection :sorted collection A sorted collection is sorting a collection by utilizing the sorting features provided by the Java collections framework. The sorting occurs order collection Order collection is sorting a collection by specifying the order-by clause for sorting this collection when retrieval.

in the memory of JVM which running Hibernate, after the data being read from database using java comparator. If your collection is not large, it If your collection is very large, will be more efficient way to it will be more efficient way to sort it. sort it .

31.What is the advantage of Hibernate over jdbc? Hibernate Vs. JDBC :JDBC 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. With JDBC, the automatic Hibernate 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. Hibernate provides

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

transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.

Hibernate provides a powerful query language Hibernate Query Language (independent JDBC supports only native from type of database) that is Structured Query Language expressed in a familiar SQL like (SQL). Developer has to find syntax and includes full out the efficient way to access support for polymorphic database, i.e. to select queries. Hibernate also effective query from a number supports native SQL of queries to perform same statements. It also selects an task. 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 Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in

amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then its essential to change object structure as well as to change code written to map table-to-object/object-totable.

XML files. If there is change in Database or in any table then the only need to change XML file properties.

Hibernate reduces lines of With JDBC, it is developers code by maintaining objectresponsibility to handle JDBC table mapping itself and result set and convert it to Java returns result to application in objects through code to use form of Java objects. It relieves this persistent data in programmer from manual application. So with JDBC, handling of persistent data, mapping between Java objects hence reducing the and database tables is done development time and manually. maintenance cost. With JDBC, caching is maintained by hand-coding. Hibernate, with Transparent Persistence, cache is set to

application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates In JDBC there is no check that version field of database table always every user has updated every time relational tuple is updated in form of Java class data. This check has to be object to that table. So if two added by the developer. users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this

tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

32.What are the Collection types in Hibernate ?


Bag Set List Array Map

33.What are the ways to express joins in HQL? HQL provides four ways of expressing (inner and outer) joins:

An implicit association join An ordinary join in the FROM clause A fetch join in the FROM clause. A theta-style join in the WHERE clause.

34.Define cascade and inverse option in one-many mapping?

cascade - enable operations to cascade to child entities. cascade="all|none|save-update|delete|all-delete-orphan" inverse - mark this collection as the "inverse" end of a bidirectional association. inverse="true|false" Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are? 35.What is Hibernate proxy? The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

36.How can Hibernate be configured to access an instance variable directly and not through a setter method ? By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

37.How can a whole class be mapped as immutable? Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application. 38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping? Criteria is a simplified API for retrieving entities by composing Criterion objects. This is a very convenient approach for functionality like "search" screens where there is a variable number of conditions to be placed upon the result set.

dynamic-update (defaults to false): Specifies that UPDATE SQL should be generated at runtime and contain only those columns whose values have changed dynamic-insert (defaults to false): Specifies that INSERT SQL should be generated at runtime and contain only the columns whose values are not null.

39.What do you mean by fetching strategy ? A fetching strategy is the strategy Hibernate will use for retrieving associated objects if the application needs to navigate the association. Fetch strategies may be declared in the O/R mapping metadata, or over-ridden by a particular HQL or Criteria query.

40.What is automatic dirty checking? Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction. 41.What is transactional write-behind? Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind. People who read this, also read:

42.What are Callback interfaces?

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

Callback interfaces allow the application to receive a notification when something interesting happens to an objectfor example, when an object is loaded, saved, or deleted. Hibernate applications don't need to implement these callbacks, but they're useful for implementing certain kinds of generic functionality.

43.What are the types of Hibernate instance states ? Three types of instance states:

Transient -The instance is not associated with any persistence context Persistent -The instance is associated with a persistence context Detached -The instance was associated with a persistence context which has been closed currently not associated

44.What are the differences between EJB 3.0 & Hibernate Hibernate Vs EJB 3.0 :Hibernate SessionCache or collection of loaded objects relating to a single unit of work XDoclet Annotations used to support Attribute Oriented Programming Defines HQL for expressing EJB 3.0 Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit Java 5.0 Annotations used to support Attribute Oriented Programming Defines EJB QL for expressing

queries to the database Supports Entity Relationships through mapping files and annotations in JavaDoc Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API Provides callback support through lifecycle, interceptor, and validatable interfaces

queries Support Entity Relationships through Java 5.0 annotations

Provides and Entity Manager Interface for managing CRUD operations for an Entity Provides callback support through Entity Listener and Callback methods

Entity Relationships are unidirectional. Bidirectional Entity Relationships are relationships are implemented bidirectional or by two unidirectional unidirectional relationships

45.What are the types of inheritance models in Hibernate? There are three types of inheritance models in Hibernate:

Table per class hierarchy Table per subclass

Table per concrete class

alcovenooses

Log in Home

Interview Questions on Hibernate For J2EE Consultants .. April 17, 2009 Print Article Citation , XML

Email

Authors

1) Adv/Disadvantages of Hibernate: a) Object Relational mapping b) The developer doesnt 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:m ysql://localhost/hibernatehibernate.connect ion.username=roothibernate.connection.passw ord= 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

_test_period=300hibernate.c3p0.acquire_incr ement=2 Disadvantages: slower in processing the queries than if the queries are used directly adding 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 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 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

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

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

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

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

Caching Strategies Once 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 wont 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 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 dont have much knowledge about the database.

13) What is NHibernate? 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.LocalSessionFactor yBean 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> <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.DriverManagerDat aSource> <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>

Interceptors can be used in cases where we may require some sort of callback methods called just before the actual operation is called. For example If it is required to log any perticular SQL in some different log/audit file, then we can set a simple Interceptor like CaptureSQL or LogSQL, just while opening Sesson using SessionFactory openSession (Interceptor) method. Following sample interceptor does the logging of SQL on 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 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 extends org.hibernate.EmptyInterceptor to become receiving callback overridden method, such as "onPrepareStatement", when ever a Session is opened, by calling SessionFactory.openSession(new CaptureSQL()). Appropriate log4j.properties file should be configured to be able to handle these logging part. My sample log4j.properties file is as follows: log4j.rootLogger=DEBUG log4j.logger.L1=INHERIT, L log4j.appender.L=org.apache.log4j.FileAppen

der log4j.appender.L.file=sample.txt log4j.appender.L.layout=org.apache.log4j.Pa tternLayout log4j.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 import import import org.hibernate.Session; org.hibernate.SessionFactory; org.hibernate.Transaction; org.hibernate.cfg.Configuration;

import org.apache.log4j.Logger; public class Client { private static final SessionFactory sessionFactory; static { try { // Create the SessionFactory from hibernate.cfg.xml

sessionFactory = new Configuration().configure().buildSessionFac tory(); } 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"); 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> <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 </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 private String private String { carName; model; segment;

public String getCarName() { return carName; } public void setCarName(String carName) { this.carName = carName; } public String getModel() {

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/hiber nate-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"/>

<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 for creation 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 written onto the sample.txt log file, as shown follows: 2009-01-04 09:01:11,578 [main] CaptureSQL Loging SQL statement .start 2009-01-04 09:01:11,593 [main] CaptureSQL This is a log statement before onPrepareStatement:

<<The DML used in this operation on the Session opened with CatureSQL as interceptor>> 2009-01-04 09:01:11,593 [main] CaptureSQL Loging SQL statement .end There are many other interesting callback methods can 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.

onDelete -> it is called just before Entity object is deleted. and many more callback methods as defined in org.hibernate.Intercept interface. Hibernate Question on Interceptor 2: Can there be any Interceptor for SessionFactory, so that it 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 callback methods of Interceptor? No, Session may not be used from the callback methods of Interceptor.

Hibernate Question on Interceptor 4: Can the collection be recreated/initialized lazily while executing any callback method from Interceptor? No, Collection may not be lazily initialized, from callback method of 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 sesssion scoped 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 Client program, and set appropriate interceptor instance into the Configuration instance, and use this interceptor while building Hibernate session factory.

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().buildSessionFacto ry(); } 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); } }

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 . com with the subject line mentioning URL for this Page (i.e, /Hibernate-Interceptorexample.php) or use this LINK. As per this website's privacy policy, we never disclose your email id, though we shall post your comments/suggestions/feedback with your name (optional) and date on this Page. If you don't want your comments/suggestions/feedback to be shared in this Page, please mention so in your email to us. Thank you very much..... If anything missed out , please let me know at techienjoy at yahoo . com

You might also like