Your SlideShare is downloading. ×
Hibernate3 q&a
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Introducing the official SlideShare app

Stunning, full-screen experience for iPhone and Android

Text the download link to your phone

Standard text messaging rates apply

Hibernate3 q&a

1,885
views

Published on

Published in: Technology

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
1,885
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
164
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. 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 themetadata 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 functions4) What are the different levels of ORM quality?There are four levels defined for ORM quality. i. Pure relational ii. Light object mappingiii. Medium object mappingiv. Full object mapping
  • 2. 5) What is a pure relational ORM?The entire application, including the user interface, is designedaround the relational model and SQL-based relationaloperations.6) What is a meant by light object mapping?The entities are represented as classes that are mapped manuallyto the relational tables. The code is hidden from the businesslogic using specific design patterns. This approach is successfulfor applications with a less number of entities, or applicationswith common, metadata-driven data models. This approach ismost known to all.7) What is a meant by medium object mapping?The application is designed around an object model. The SQLcode is generated at build time. And the associations betweenobjects are supported by the persistence mechanism, and queriesare specified using an object-oriented expression language. Thisis best suited for medium-sized applications with some complextransactions. Used when the mapping exceeds 25 differentdatabase products at a time.8) What is meant by full object mapping?Full object mapping supports sophisticated object modeling:composition, inheritance, polymorphism and persistence. Thepersistence layer implements transparent persistence; persistentclasses do not inherit any special base class or have toimplement a special interface. Efficient fetching strategies and
  • 3. caching strategies are implemented transparently to theapplication.9) What are the benefits of ORM and Hibernate?There are many benefits from these. Out of which the followingare 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? Sessionsession =getSessionFactory().openSession(); Transactiontx =session.beginTransaction();
  • 4. MyPersistanceClassmpc = newMyPersistanceClass ("Sample App"); session.save(mpc); tx.commit(); session.close();The Session and Transaction are the interfaces provided byhibernate. There are many other interfaces besides this.Q. How will you configure Hibernate?Answer:The configuration files hibernate.cfg.xml (orhibernate.properties) and mapping files *.hbm.xml are used bythe Configuration class to create (i.e. configure and bootstraphibernate) the SessionFactory, which in turn creates the Sessioninstances. Session instances are the primary interface for thepersistence 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 theclasspath then hibernate.cfg.xml file overrides the settings foundin the hibernate.properties file." Mapping files (*.hbm.xml): These files are used to mappersistent objects to a relational database. It is the best practiceto store each object in an individual mapping file (i.e mapping
  • 5. file per class) because storing large number of persistent classesinto 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 amapping file named Account.hbm.xml. Alternatively hibernateannotations can be used as part of your persistent class codeinstead 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 isthreadsafe so that many threads can access it concurrently andrequest for sessions and immutable cache of compiled mappingsfor a single database. A SessionFactory is usually only builtonce at startup. SessionFactory should be wrapped in some kindof singleton so that it can be easily accessed in an applicationcode.SessionFactorysessionFactory = newConfiguration().configure().buildSessionfactory();Q. What is a Session? Can you share a session objectbetween different theads?Answer:Session is a light weight and a non-threadsafe object (No, youcannot share it between threads) that represents a single unit-of-
  • 6. work with the database. Sessions are opened by aSessionFactory and then are closed when all work is complete.Session is the primary interface for the persistence service. Asession obtains a database connection lazily (i.e. only whenrequired). To avoid creating too many sessions ThreadLocalclass can be used as shown below to get the current session nomatter how many times you make call to the currentSession()method.&public class HibernateUtil {&public static final ThreadLocal local = new ThreadLocal();public static Session currentSession() throwsHibernateException {Session session = (Session) local.get();//open a new session if this thread has no sessionif(session == null) {session = sessionFactory.openSession();local.set(session);}return session;}}It is also vital that you close your session after your unit of workcompletes. Note: Keep your Hibernate Session API handy.Q. What are the benefits of detached objects?
  • 7. Answer:Detached objects can be passed across layers all the way up tothe presentation layer without having to use any DTOs (DataTransfer Objects). You can later on re-attach the detachedobjects 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, itis the best practice to break the long transaction up into two ormore transactions. You can use detached objects from the firsttransaction to carry data all the way up to the presentation layer.These detached objects get modified outside a transaction andlater on re-attached to a new transaction via another session.Cons" In general, working with detached objects is quitecumbersome, and better to not clutter up the session with them ifpossible. It is better to discard them and re-fetch them onsubsequent requests. This approach is not only more portable butalso more efficient because - the objects hang around inHibernates cache anyway." Also from pure rich domain driven design perspective it isrecommended to use DTOs (DataTransferObjects) and DOs
  • 8. (DomainObjects) to maintain the separation between Serviceand 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 anew object. This does work only for Hibernate managedsurrogate 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
  • 9. intended for reattaching a detached object. Thesession.lock() method simply reattaches the object to thesession without checking or updating the database on theassumption that the database in sync with the detachedobject. It is the best practice to use either session.update(..)or session.saveOrUpdate(). Use session.lock() only if youare absolutely sure that the detached object is in sync withyour detached object or if it does not matter because youwill be overwriting all the columns that would havechanged later on within the same transaction.Note: When you reattach detached objects you need tomake sure that the dependent objects are reatched as well.Q. How would you reatach detached objects to a sessionwhen the same object has already been loaded into thesession?You can use the session.merge() method call.Q. What are the general considerations or best practicesfor defining your Hibernate persistent classes?1.You must have a default no-argument constructor foryour persistent classes and there should be getXXX()(i.eaccessor/getter) and setXXX( i.e. mutator/setter)methods for all your persistable instance variables.2.You should implement the equals() and hashCode()
  • 10. 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.UseXDoclet 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?
  • 11. 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 howdoes 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 inhibernate?17)What are different environments to configure hibernate?18)What is the file extension you use for hibernate mappingfile?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 beeasily accessed?
  • 12. 23)What are POJOs?24)What is object/relational mapping metadata?25)What is HQL?26)What are the different types of property and classmappings?27)What is Attribute Oriented Programming?28)What are the different methods of identifying an object?29)What are the different approaches to represent aninheritance hierarchy?30)What are managed associations and hibernateassociations?Question :If you want to react programmatically whileexecuting methods of Hibernate sessioninstance, what are various ways toaccomplish this while using Hibernate?Answer :By using Hibernate Event system and/orHibernate Interceptors provided byHibernate API, one can provide customizedhandlers and listeners for reactingprogrammatically to the execution ofvarious methods from Hibernate session
  • 13. instance.Question :What will happen if there is a instancelevel variable defined within eventlistener code?Answer :As instance of Listener class file areshared across multiple requests, soit is not alright to use instance levelvariable within Listener class file,as far as thread-safe behavior isconcerned, and unless the variable value isto be used in multiple request perspective.HibernateIntervie Does Hibernate Session Object hasw any cache associated with it by default ?Questions 1:Hibernat Yes, first-level caching is a mandatory requirement for Hibernate
  • 14. e Session Object.InterviewAnswer1:HibernateIntervie Is there any cache associated withw Hibernate SessionFactory Object?Questions 2:Hibernate Yes, there is an optional second-Intervie level cache with Hibernatew SessionFactoryAnswer object.2:Hibernate Can a single Hibernate SessionIntervie object be used across multiplew threadsQuestion running within a processs 3:
  • 15. Hibernate No, Hibernate Session is basicallyIntervie single-threaded and not to be usedw acrossAnswer multiple threads.3:HibernateIntervie Is this same for Hibernatew SessionFactory object as well?Questions 4:Hibernate No, Hibernate SessionFactory isIntervie basically thread-safe, thus can bew re-used across multiple threads and multipleAnswer Transacions as well.4:Hibernat How can the second-level caching fore Hibernate SessionFactory object beIntervie disabled?wQuestion
  • 16. s 5:Hibernat By setting appropriatee hibernate.cache configuration related properties, oneIntervie can enable/disable second-levelw caching for Hibernate SessionFactoryAnswer object5: but only for once before SessionFactory is createdHibernate Is it possible to use HibernateIntervie Session object with the scope andw contextQuestion defined by JTA Transaction ?s 6:Hibernat Yes, starting with Hibernate 3.0.1e version, Sessionfactory.getCurrentSessionIntervie methodw has the scope and context defined byAnswer the running JTA Transaction scope6: and context. But as of Hibernate 3.1 version, getCurrentSession method of Hibernate SessionFactory has the current Session Scope and Context controlled by pluggable
  • 17. current Session Context class, defined in configuration parameter such as hibernate.current_session_context_cl ass.Hibernate As of Hibernate 3.1 version can youIntervie be able to explain how many waysw scope and context of Hibernate current contextual session beQuestion handled?s 7:Hibernat As of Hibernate 3.1 version,e Hibernate has three ways to handleIntervie current contextualw session, such as JTASessionContextAnswer ThreadLocalSessionContext7: ManagedSessionContext.Hibernate Interview Questions 1 :What is the difference between class tagand component tag in Hibernatefrom the persistence perspective?Hibernate Interview answer 1 :class tag refers to an Entity that ispersisted with an identifier,
  • 18. while component tag means the POJOassociated with component tag ispersisted along with contained object as avalue type.So it doesnt requirean identifier, while the contained objecthas an entity reference, not for thecomponent object.Hibernate Interview Questions 2 :What is the difference between componentand dynamic component?Hibernate Interview answer 2 :Component in Hibernate world, meanssomething that is embeded ina contained object and there exist acomposition style of binding betweenthe contained object and the componentobject. So component is declaredinside a class tag, just to say one type ofuse.Dynamic-component has the samecharacteristics as component but thereexistsa difference in the way dynamic-componentcan be used to map a beans attribute,this can be of type java.util.Map with thekey defined in mapping fileand corresponding value from the tablescolumn.
  • 19. So with dynamic-component, there can bepossibility of changing the attributekey/value pair during deployment time, justby changing the name andcolumn values in the mapping configurationfile.Hibernate Interview Question :What are the different types of Modes areavailable, those can beused along with Hibernate Session?Hibernate Interview Answer :Various Modes like CacheMode, LockMode,EntityMode, FlushMode,ScrollMode, these modes can be used alongwith Hibernate Session.Hibernate Interview Question :What are the various CacheMode available inHibernate Version 3.2?Hibernate Interview Answer :Various CacheMode like GET, IGNORE, NORMAL,PUT, REFRESH areavailable with Hibernates second-levelcache.Hibernate Interview Question :
  • 20. Is there any way not to use Hibernatessecond-level cache, whileusing operations of Hibernate Session?Hibernate Interview Answer:By setting CacheMode.IGNORE as the cachemode for any HibernateSession instance, before any operation onthat session is carriedout. This way one can ignore Hibernatessecond-level cache whileusing operations of Session.Hibernate Interview Question :How to disable Hibernates second-levelcache from usage?Hibernate Interview Answer:Just by providing cache provider asorg.hibernate.cache.NoCacheProvider, one can disable use of Hibernates secondlevel cache.Another way is by settinguse_second_level_cache from hibernate.cacheproperty, as false.Another way is to use CacheMode.IGNOREalong with Hibernates session.Hibernate Interview Question :What are the various steps to useHibernates second-level cache
  • 21. Hibernate Interview Answer:One has to define the supporting cacheprovider for any second-levelcache framework to be used, in Hibernateconfiguration file along withthe configuration forHibernatesSessionFactory.Then it is required to enable theuse_second_level_cache propertyas true or providing appropriate cachemapping at class or collectionmapping related configuration.Hibernate Interview Question :What are the various types of cacheproviders support available withHibernates second-level cache features inapi?Hibernate Interview Answer:Various cache providers likeEhCacheProvider, HashtableCacheProvider,JndiBoundTreeCacheProvider,OptimisticTreeCacheProvider,OSCacheProvider, SwarmCacheProvider and TreeCacheProvideretc.Hibernate Interview Question :
  • 22. If the project requirement to have thesecond level cache used in transactionalcontext, which cache would you choose outof those Cache Providers?Answer:JBossTreeCache cache provider and cacheframework can be a choice,as it can be used in clustered environmentwith ip multicast replicationmode. And this cache can be used along witha transactional context.Hibernate Interview Question : How about EHCache and OSCache providersfrom Hibernate version 3.0,can these be used in clustered environment,as of this version?Answer: No, these cache providers are capable ofrunning in-memory and diskmodes, with no cluster way of execution.Hibernate Interview Question : How can you avoid synchronization ofpersistent objects with the
  • 23. database, and do not want to retain thisobject in the first-levelcache, when flush method is called onsession?Answer: By using evict method from session, onecan remove specific objectfrom first-level cache of session, and thuscan avoid automaticsynchronization of object with database,when flush method is calledon session instance.Hibernate Interview Question : Can you be able to evict all objects fromthe session cache? If yes, How?Answer: Yes, it is possible to evict all objectsfrom the session cache by usingclear method on session instance.Hibernate Interview Question : If anyone wants to perform similaractivities with Hibernates second-levelcache, is it possible? If yes, how?Answer:
  • 24. Yes, evict object(s) with or withoutcriteria can be possible onHibernates second-level cache by usingmethods on HibernatesSessionFactory, and methods are evict,evictCollection and manymore arguments available.Hibernate Question : What are the different TransactionFactories available with Hibernate?Hibernate Answer :There are three different types ofTransaction Factoryavailable withHibenate 3.2 as JDBCTransactionFactory,JTATransactionFactory andCMTTransactionFactory.Hibernate Question :Which one is the default transactionfactory in Hibernate 3.2?Hibernate interview answerJDBCTransactionFactory is the defaultlocaltransaction factory withHibernate 3.2.
  • 25. Hibernate interview questionCan Hibernate Session Factory be bound toJNDI?Hibernate interview answerYes, by configuring in hibernate.cfg file,sessionfactory can be bound to initial context (asdefined byproperties hibernate.jndi.url andhibernate.jndi.class).Hibernate interview questionCan Hibernate be used to callstored procedures and SQLstatements?Hibernate interview answerYes, there are provision in Hibernate 3.2,for definingcallable statements and SQL in mapping HBMfiles.Hibernate interview questionCan the custom SQL be defined for creationof Java entityobject by loading values from databasetables andpopulating Java Object?
  • 26. Hibernate interview answerYes, Javaentity objects can be loaded withcustom SQLqueries and can be defined in HBM file inform ofHQL (Hibernate Query Language).Hibernate interview questionWhat are the different Fetching Strategiesavailablewith Hibernate 3.2?Hibername interview answerThere are four different Fetching standardsavailable inHibernate3.2, as follows: join fetching,select fetching,batch fetching, sub-select fetching.Hibernate interview questionWhat are the different types of statisticsavailable inHibernate 3.2?Hibernate interview answerDifferent types of statistics likeQueryStatistics,CategorizedStatistics,CollectionStatistics, EntityStatisticsetc., available in Hibernate 3.2.
  • 27. Hibernate interview questionHow can you get a handle on HibernateStatistics?Hibernate interview answerIf Hibernate is deployed in a JMX enabledApplicationserver, then Hibernate provided astatistics service,that can be registered as MBean with JMXserver and beused to retrieve different types ofstatistics available.Hibernate statistics can be obtained fromsessionfactory as well.Hibernate interview questionCan Hibernate be used to map persistententity POJO toXML files?Hibernate interview answerYes, Hibernate can be used to mapp XMLfile/tags toPOJO entity classes.Hibernate Question : If there aremultiple databases to be used to interactwith domain
  • 28. classes, how can session factory be able tomanagemultipledatasources?Hibernate Answer : Each datasource will be configured to eachsessionfactory, and to use a single database, asession iscreated to use database.Question : What is lazy initialization inHibernate?Answer :When there is an association of one-to-one,orone-to-many, or many-to-many betweenclasses,and on creation of one object, it has to bedecided whether to bring associated objectsalongwith this object or not. By settinglazy="true"we instruct Hibernate not to bring theassociatedobject/objects during creation of therequired object.By setting lazy="false", it is the reverse,this means
  • 29. we instruct Hibernate to bring all theassociatedobjects also at the time of returning theassociatingobject.Hibernate interview Question : if there anyimpact on performanceby this attribute lazy ?Hibernate interview Answer :This is purely a configuration timedecision one hasto take to use lazy attribute and its value(true/false)appropriately. As SessionFactory is createdonce and reused,all the configuration setting in HBM fileis read once,andcannt be changed at runtime.Hibernate Question : What are the differentstatesof an instance in Hibernate?Hibernate Answer :There are three states that exist for anyinstance of aclass. These are transient, persistent anddetached.
  • 30. Those instances that are created but notassociated withany session or not saved in database aretrasient objects.Those instances that are created and beused in any of themethods like save, saveOrUpdate, update ofSession arecalled persistent objects.Those instances that were used in Sessionmethods like save,saveOrUpdate or update to be inserted orupdated in databasetable, and then session is flushed andclosed, now theseobjects are in JVM, but these are not boundto any session.Hibernate interview questionHow can certain type of logic executed onexecution ofCRUD operation of session, withoutduplicating it acrossmany places in code base?Hibernate interview answerHibernate Interceptors can be used toreceive callbackfor certain type of events or operationslike save, delete,
  • 31. load, update of session. Session Factorylevel interceptorand session level interceptor. TheseInterceptors can beused to have code for certain type of logicto be calledfor every lifecycle method of session.Hibernate interview questionHow can multiple threads access sessionfactorysimulteneously to create session instance?Hibernate interview answersession factory is thread-safe, so it isokay to be usedby many threads to have session fromsession factory,but I think session is not thread safe andit should beused by one thread at a time, and afteruse,session has to be flushed and closed.Hibernate interview questionHow many ways Hibernate manages concurrency?Hibernate interview answerHibernate has different ways of managingconcurrency.
  • 32. These are automatic versioning, detachedobject andextended user sessions.Hibernate interview questionWhat is the difference between uni-directional andbi-directional associations?Hibernate interview answeruni-directional association allows objectcreation fromone direction only. Bi-directionalassociation allowsobject querying from both directions offetching objectinstances.A->B, now querying A, can provideinformation on B aswell, based on lazy parameter, but in caseof A<->B,querying either A or B, will have value ofB or A aswell, respectively.Hibernate interview QuestionWhat are the different contextual sessionin Hibernate?Hibernate interview answer
  • 33. There are three different types ofcontextual session Hibernateprovides, these are JTA session context,local thread sessioncontext and managed session context. JTAsession context isapplicable in case Hibernate session isrunning in JTA (JavaTransaction API), request thread levelsession scoped applicablein case of local thread session, andmanaged session, requiresapplication to open, close and flushsession, so creation ofsession should be handled by applicationonly.Hibernate interview QuestionCan you tell us difference betweenHibernate HQL over SQL?Hibernate interview answerHQL is fully object oriented, with supportfor objectinheritence, polymorphism and association,but SQLis more of Relational with structured formof queries.Hibernate interview Question
  • 34. What are the different scopes one canintroduce while usingInterceptors with Hibernate?Hibernate interview AnswerProbably, one can use interceptors withhibernate Sessionscoped or SessionFactory scoped contexts,while usingInterceptors with Hibernate.Hibernate interview QuestionHow many ways client application that usesHibernate toreact to certain events?Hibernate interview AnswerProbably, if I am not wrong, two ways onecan react/actto certain events generated out ofHibernate Framework.These are either Interceptors or eventsystems.Hibernate interview QuestionCan I be able to persist a XML DOM objecttree to databaseby defining mapping between XML DOM todatabase table,without using POJOs?
  • 35. Hibernate interview AnswerYes, one can use Hibernate mapping topersist XML DOM treehierarchy to database tables.Hibernate Interview Question :Suppose Hibernate Filters are defined inHBM file for a class,but need is to not use this filter atruntime, Is it possible?Hibernate Interview Answer :Hibernate Filters are to be enabled for anyinstance of Hibernatesession before use. So whenever is it notrequired, those filterswont be used.Hibernate Interview Question :How can the Hibernate Filter be enabled/disabled for a session?Hibernate Interview answer :session.enableFilter(methodparameters/arguments) is the method forenabling/disabling filter for HibernateSession instance.Hibernate Interview Question :
  • 36. In case of a requirement as to usecombination of fields from differentclass files those are mapped to differenttables. Or in short the requirementis to have functionality of a view(database perspective) but not create aview in database.Hibernate Interview answer :Yes, using Hibernate Filters one can definecertain filter conditions indifferent class file mapping so as tofilter the final query result as perthe mapping and filter definition.Hibernate Interview Question :What are the various persistent objectsfetching strategies defined inHibernate3 ?Hibernate Interview Answer :There are four different types ofpersistent objects fetching strategiesdefined in Hibernate3, such as Joingfetching, select fetching, Sub-selectfetching and Batch fetching strategies.Hibernate Interview Question :Can these fetching strategies forretrieving persistent objects, those are
  • 37. defined in Object Relational Mapping inconfiguration, be able to over-ridden ?Hibernate Interview answer :Yes, fetching strategies as defined inMapping configuration files can beover-ridden by using HQL or Criteriadefined/used with Hibernate Sessioninstance.Hibernate Interview Question :Can the property tag definition of theclass tag for the POJO class that is beingused in O/R Mapping, be lazily loaded byusing lazy="true"?Hibernate Interview Answer :Yes, we can define lazy="true" for anyproperty within a class tag from theO/R mapping file. But we must have to applyproper instrumentation of the build-timebytecode of the class that is being used,or else this lazy definition will beignoredwhile fetching respective persistentobject.Hibernate Interview Question :
  • 38. While working with large binary stream orserializable object to be used withdatabaseusing Hibernate Session, is there anysetting that is to be used in Hibernatespecificconfiguration file?Hibernate Interview Answer :Yes, hibernate.jdbc.use_streams_for_binarysetting can be used with value true orfalse,in case you want to use large binary orserializable data to/from database.Hibernate Interview Question :While using outer join fetch strategy, canyou impose certain depth or level of objecthierarchy to be fetched?Hibernate Interview Answer :Yes, one can impose certain depth or levelof object hierarchy to be fetched whileusingouter join fetch strategy, by using theconfiguration setting ashibernate.max_fetch_depthwith some count number.Hibernate Interview Question :
  • 39. In case of highly concurrent database usagemode, can you set for all updates on tabletobe executed based on primary key column ofthe table, for which column data to beupdated?Hibernate Interview Answer :Yes, by using hibernate.order_updates astrue or false for achieving/forcing thistype ofupdates based on primary key column values.Hibernate Interview Question :Suppose you have encountered a situationwhereby cluster aware second level cache isnotperforming properly or upto desiredexpectation level while working wihtHibernate.Is there any setting that you can rememberthat can help by minimizing number ofupdatesor object put calls, thus can help inincreasing performance of read from cachein clusterenvironment?Hibernate Interview Answer :hibernate.cache.use_minimal_puts setting inHibernate configuration file, with a value
  • 40. as true or false, would optimize Hibernatesecond-level cache by minimizing number ofadditions/updations to objects those arebeing cached, thus minimizing overheadassociatedwith number of reads from database.Hibernate Interview Question :How can you log all seond-level cacherelated activities while using HibernateFramework?Hibernate Interview Answer :By using the Log category"org.hibernate.cache", one can obtain logrelated to Hibernatessecond-level cache activities.Hibernate Interview Question :What are the Transaction Strategiesavailable with Hibernate Framework?Hibernate Interview Answer :Various transaction strategies available inHibernate as such are forJDBC, JTA and CMT with relatedTransactionFactories.Hibernate Interview Question :
  • 41. Does Hibernate as of latest version,provide support for use defined TransactionFactories?Hibernate Interview Answer :Yes, as of latest version of HibernateFramework, custom/use defined/suppliedTransactionFactories can be used, by definingappropriate factory class file for thesetting"hibernate.transaction.factory_class."Disclaim: These materials mentioned asabove, are respective Authors ownunderstanding ofHibernate Framework, for details andcomplete information, please refer toHibernate web-sitehttp://www.hibernate.org/If anything missed out , please let me knowattechienjoy at yahoo . comHibernate Example on Filter Hibernate class
  • 42. Criteria : heirarchymapping :Example on using Hibernate Example onFilter Criteria mappingusing Hibernate class hierarchy usingFramework to work various wayswith. of persisting into database tables.Hibernate one to many Hibernate one to one mappingmapping Example : Example :one to many mapping one to one mappingexplained using an explained using anexample exampleand Hibernate and HibernateFramework. Framework.Hibernate Example on Hibernate Join Example :composite Primary key : Using Table joinExample on using explained with anHibernate Framework exampleto work with mapping while using Hibernateusing composite Framework.Primary key.Hibernate Property Formula : Hibernate Named Query Example :Hibernate Example onProperty Named Query markupTag with ease to do using an example
  • 43. code walk-through and Hibernate Framework.Hibernate Transaction onJBoss : Hibernate Interview Questions :ExplainingTransaction using Interview QuestionsHibernate on Hibernate withonJBoss Application answer.Server.Hibernate Bag Mapping Hibernate Many to ManyExample : Mapping Example :class mapping using Many to many mappingBag Tag example using example usingHibernate HibernateFramework and a Framework and asimple to follow simple to followsteps. steps.List of Examples on Hibernate Hibernate Example on Filter :: Example on using Filter usingList of example using Hibernate FrameworkHibernate. to work with.Class Hierarchy Mapping Hibernate ComponentExample : Property :class hierarchy Hibernate Example on
  • 44. mapping example using ComponentHibernate with source codeFramework and a explained.simple to followsteps.Hibernate Interceptor Hibernate one to manyExample : mapping Example :Example on using one to many mappingInterceptor using explained using anHibernate Framework examplewith source code and Hibernateexplained. Framework.Example on persisting Class Hibernate Insert UpdateHierarchy : control :Example on using Hibernate Example onHibernate Framework controllingto persist Class insert and updateHierarchy into attributesdatabase.1.What is ORM ?ORM stands for object/relational mapping. ORM is theautomated persistence of objects in a Java application to thetables in a relational database.
  • 45. 2.What does ORM consistsof ?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 fetching3.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) andpersistence framework that allows you to map plain old Javaobjects to relational database tables using (XML) configurationfiles.Its purpose is to relieve the developer from a significantamount of relational data persistence-related programming tasks.
  • 46. 5.Why do you need ORMtools like hibernate?The main advantage of ORM like hibernate is that it shieldsdevelopers from messy SQL. Apart from this, ORM providesfollowing 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 you6.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
  • 47. 7.What is the need for Hibernate xml mapping file?Hibernate mapping file tells Hibernate which tables and columnsto use to load and store objects. Typical mapping file look asfollows:8.What are the most common methods of Hibernateconfiguration?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:
  • 48. 10.What are the Coreinterfaces are ofHibernate framework? People who read this, also read:-The five core interfaces JSF Interview Questionsare used in just about Core Java Questionsevery Hibernate J2EE Certificationapplication. Using these Let Spring Manage JSF Beansinterfaces, you can store JDBC Interview Questionsand retrieve persistentobjects and controltransactions. Session interface SessionFactory interface Configuration interface
  • 49. Transaction interface Query and Criteria interfaces 11.What role does theSession interface play in Hibernate?The Session interface is the primary interface used by Hibernateapplications. It is a single-threaded, short-lived objectrepresenting a conversation between the application and thepersistent store. It allows you to create query objects to retrievepersistent 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 identifier12.What role does the SessionFactory interface play inHibernate?The application obtains Session instances from aSessionFactory. There is typically a single SessionFactory forthe whole applicationå¹¼reated during application initialization.
  • 50. The SessionFactory caches generate SQL statements and othermapping metadata that Hibernate uses at runtime. It also holdscached data that has been read in one unit of work and may bereused in a future unit of workSessionFactorysessionFactory =configuration.buildSessionFactory();13.What is the general flow of Hibernate communication withRDBMS?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 objects14.What is Hibernate Query Language (HQL)?Hibernate offers a query language that embodies a verypowerful and flexible mechanism to query, store, update, andretrieve objects from a database. This language, the Hibernatequery Language (HQL), is an object-oriented extension to SQL.
  • 51. 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> <classname="com.test.User" table="user"> <propertycolumn="USER_NAME"length="255" name="userName"not-null="true"type="java.lang.String"/> <propertycolumn="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()?load() vs. get() :- load() get()
  • 52. Only use the load() method if If you are not sure that theyou are sure that the object object exists, then use one ofexists. the get() methods.load() method will throw an get() method will returnexception if the unique id is not null if the unique id is notfound in the database. found in the database.load() just returns a proxy bydefault and database won’t be get() will hit the databasehit 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 containan already persistent instance with the same identifier, andmerge() if you want to merge your modifications at any timewithout consideration of the state of the session.18.How do you define sequence generated primary key inhibernate?Using <generator> tag.Example:-
  • 53. <idcolumn="USER_ID"name="id"type="java.lang.Long"><generatorclass="sequence"><paramname="table">SEQUENCE_NAME</param> <generator></id>19.Define cascade andinverse 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 abidirectional association.inverse="true|false"Essentially "inverse" indicates which end of a relationshipshould be ignored, so when persisting a parent who has acollection of children, should you ask the parent for its list ofchildren, 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 documentand called wherever required.Example:<sql-query name = "empdetails"><returnalias="emp"class="com.test.Employee"
  • 54. /> 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-queryname="selectAllEmployees_SP"callable="true"><returnalias="emp"class="employee"> <return-propertyname="empid"column="EMP_ID"/><return-propertyname="name"column="EMP_NAME"/><return-
  • 55. propertyname="address"column="EMP_ADDRESS"/> { ? = call selectAllEmployees() }</return></sql-query>22.Explain Criteria APICriteria is a simplified API for retrieving entities by composingCriterion objects. This is a very convenient approach forfunctionality like "search" screens where there is a variablenumber 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.DefineHibernateTemplate?org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different methodsfor querying/retrieving data from the database. It also converts
  • 56. checked HibernateExceptions into uncheckedDataAccessExceptions.24.What are the benefits does HibernateTemplate provide?The benefits of HibernateTemplateare : 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 switchbetween relational databases without code changes?Using Hibernate SQL Dialects , we can switch databases.Hibernate will generate appropriate hql queries based on thedialect defined.26.If you want to see the Hibernate generated SQL statementson console, what should we do?In Hibernate configuration file set as follows:<propertyname="show_sql">true</property>
  • 57. 27.What are derived properties?The properties that are not mapped to a column, but calculated atruntime by evaluation of an expression are called derivedproperties. The expression can be defined using the formulaattribute oftheelement. People who read this, also read:- BREW Interview Questions BREW Questions SCWCD Certification28.What is AJAX Form Validation Using DWR and Springcomponent Servlets Interview Questionsmapping inHibernate? 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 supportedExample:
  • 58. 29.What is the difference between sorted and orderedcollection in hibernate?sorted collection vs. order collection :- sorted collection order collectionA sorted collection is sorting a Order collection is sorting acollection by utilizing the collection by specifying thesorting features provided by order-by clause for sorting thisthe Java collections collection when retrieval.framework. The sorting occurs
  • 59. in the memory of JVM whichrunning Hibernate, after thedata being read from databaseusing 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 tosort it. sort it .31.What is the advantage of Hibernate over jdbc?Hibernate Vs. JDBC :- JDBC Hibernate Hibernate is flexible andWith JDBC, developer has to powerful ORM solution to mapwrite code to map an object Java classes to database tables.models data representation to Hibernate itself takes care ofa relational data model and its this mapping using XML files socorresponding database developer does not need toschema. write code for this.With JDBC, the automatic Hibernate provides
  • 60. mapping of Java objects with transparent persistence anddatabase tables and vice versa developer does not need toconversion is to be taken care write code explicitly to mapof by the developer manually database tables tuples towith lines of code. application objects during interaction with RDBMS. Hibernate provides a powerful query language Hibernate Query Language (independentJDBC supports only native from type of database) that isStructured Query Language expressed in a familiar SQL like(SQL). Developer has to find syntax and includes fullout the efficient way to access support for polymorphicdatabase, i.e. to select queries. Hibernate alsoeffective query from a number supports native SQLof queries to perform same statements. It also selects antask. effective way to perform a database manipulation task for an application.Application using JDBC to Hibernate provides thishandle persistent data mapping itself. The actual(database tables) having mapping between tables anddatabase specific code in large application objects is done in
  • 61. amount. The code written to XML files. If there is change inmap table data to application Database or in any table thenobjects and vice versa is the only need to change XMLactually to map table fields to file properties.object properties. As tablechanged or database changedthen it’s essential to changeobject structure as well as tochange code written to maptable-to-object/object-to-table. Hibernate reduces lines ofWith JDBC, it is developer’s code by maintaining object-responsibility to handle JDBC table mapping itself andresult set and convert it to Java returns result to application inobjects through code to use form of Java objects. It relievesthis persistent data in programmer from manualapplication. So with JDBC, handling of persistent data,mapping between Java objects hence reducing theand database tables is done development time andmanually. maintenance cost.With JDBC, caching is Hibernate, with Transparentmaintained by hand-coding. Persistence, cache is set to
  • 62. 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 updatesIn JDBC there is no check that version field of database tablealways every user has updated every time relational tuple isdata. This check has to be updated in form of Java classadded by the developer. 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
  • 63. 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 Collectiontypes in Hibernate ? Bag Set List Array Map33.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?
  • 64. 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 abidirectional association.inverse="true|false"Essentially "inverse" indicates which end of a relationshipshould be ignored, so when persisting a parent who has acollection of children, should you ask the parent for its list ofchildren, or ask the children who the parents are?35.What is Hibernate proxy?The proxy attribute enables lazy initialization of persistentinstances of the class. Hibernate will initially return CGLIBproxies which implement the named interface. The actualpersistent object will be loaded when a method of the proxy isinvoked.36.How can Hibernate beconfigured to access an instance variable directly and notthrough a setter method ?By mapping the property with access="field" in Hibernatemetadata. This forces hibernate to bypass the setter method andaccess the instance variable directly while initializing a newlyloaded object.
  • 65. 37.How can a whole class be mapped as immutable?Mark the class as mutable="false" (Default is true),. Thisspecifies that instances of the class are (not) mutable. Immutableclasses, may not be updated or deleted by the application.38.What is the use of dynamic-insert and dynamic-updateattributes in a class mapping?Criteria is a simplified API for retrieving entities by composingCriterion objects. This is a very convenient approach forfunctionality like "search" screens where there is a variablenumber 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 forretrieving associated objects if the application needs to navigatethe association. Fetch strategies may be declared in the O/Rmapping metadata, or over-ridden by a particular HQL orCriteria query.
  • 66. 40.What is automatic dirtychecking?Automatic dirty checking is a feature that saves us the effort ofexplicitly asking Hibernate to update the database when wemodify the state of an object inside a transaction.41.What is transactional write-behind?Hibernate uses a sophisticated algorithm to determine anefficient ordering that avoids database foreign key constraintviolations but is still sufficiently predictable to the user. Thisfeature is calledtransactionalwrite-behind. People who read this, also read:- JDBC Interview Questions42.What are JDBC QuestionsCallback Struts Tutorialinterfaces? JSF Integration with Spring Framework JSP Interview QuestionsCallbackinterfaces allow the application to receive a notification whensomething interesting happens to an object—for example, whenan object is loaded, saved, or deleted. Hibernate applicationsdont need to implement these callbacks, but theyre useful forimplementing certain kinds of generic functionality.
  • 67. 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 associated44.What are the differences between EJB 3.0 & HibernateHibernate Vs EJB 3.0 :- Hibernate EJB 3.0 Persistence Context-Set ofSession–Cache or collection of entities that can be managedloaded objects relating to a by a given EntityManager issingle unit of work defined by a persistence unitXDoclet Annotations used to Java 5.0 Annotations used tosupport Attribute Oriented support Attribute OrientedProgramming ProgrammingDefines HQL for expressing Defines EJB QL for expressing
  • 68. queries to the database queriesSupports Entity Relationships Support Entity Relationshipsthrough mapping files and through Java 5.0 annotationsannotations in JavaDocProvides a Persistence Provides and Entity ManagerManager API exposed via the Interface for managing CRUDSession, Query, Criteria, and operations for an EntityTransaction APIProvides callback support Provides callback supportthrough lifecycle, interceptor, through Entity Listener andand validatable interfaces Callback methodsEntity Relationships areunidirectional. Bidirectional Entity Relationships arerelationships are implemented bidirectional orby two unidirectional unidirectionalrelationships45.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
  • 69. Table per concrete classalcovenooses Log in HomeInterview Questions on HibernateFor J2EE Consultants ..April 17, 2009Print ArticleCitation, XML EmailAuthors
  • 70. 1) Adv/Disadvantages of Hibernate:a) Object – Relational mappingb) The developer doesn’t have to take into account the type ofdatabase he is coding for. The type of database can be changedby 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 ofthe object he wants to be loaded. (Fetching and join strategy)f) Connection Pooling can be done by editing a few lines in thehibernate-cfg.xml file .. c3p0 :- connection pool built in with Hibernatehibernate.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=falsehibernate.c3p0.max_size=1hibernate.c3p0.min_size=0hibernate.c3p0.timeout=5000hibernate.c3p0.max_statements=100hibernate.c3p0.idle
  • 71. _test_period=300hibernate.c3p0.acquire_increment=2Disadvantages:slower in processing the queries than if the queries areused directlyadding the xml would cause portability problems**What is Component mapping?Answers:* A component is an object saved as a value, not as areference* A component can be saved directly without needing todeclare interfaces or identifier properties* Required to define an empty constructor* Shared references not supported2) Explain Session Factory?SessionFactory is Hibernate’s concept of a single datastore andis threadsafe so that many threads can access it concurrentlyand request for sessions and immutable cache of compiledmappings for a single database. A SessionFactory is usually onlybuilt once at startup. SessionFactory should be wrapped insome kind of singleton so that it can be easily accessed in anapplication code.
  • 72. SessionFactorysessionFactory = newConfiguration().configure().buildSessionfactory3) Explain different type of fetch statements?Fetching strategy is used by hibernate to retrieve associatedobjects 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 willfetch the associated instance/ collection using outer join.fetch = select This is the default option. If there are ‘n’ associatedobjects to the one you requested then there would be ‘n+1′select statements executed. If the lazy=true then these wouldexecuted only when the association is required.fetch = subselect A second select statement would be used to get all therelated objects. If the lazy=true then this second selectstatement would be executed only when the association iscalled.fetch=batch
  • 73. It is an optimization strategy for fetch=select , where inusing a list of primary or foreign keys one would pull out allinstances/collection in a single select.4) Explain lazy loading?5) Explain object states?TransientPersistentDetached: Detached objects have a representation in databasebut changes done to the object won’t be reflected to thedatabase. A detached objects can be created by closing thesession or by using the evict method of the session on theobject. In order to reflect the changes in the object to thedatabase the load,refresh,merge,update or save method on theobject in any session.6) Performance metrics in Hibernate?sessionFactory.getStatistics7) What is the difference between the session.get()method and the session.load() method?Both the session.get(..) and session.load() methods create apersistent object by loading the required object from thedatabase. But if there was not such object in the database then
  • 74. the method session.load(..) throws an exception whereassession.get(…) returns null8) Explain caching in HibernateHibernate uses two different caches for objects: first-levelcache and second-level cache. First-level cache is associatedwith the Session object, while second-level cache is associatedwith the Session Factory object. By default, Hibernate uses first-level cache on a per-transaction basis. Hibernate uses thiscache mainly to reduce the number of SQL queries it needs togenerate within a given transaction. For example, if an object ismodified several times within the same transaction, Hibernatewill generate only one SQL UPDATE statement at the end of thetransaction, containing all the modifications. This articlefocuses on second-level cache. To reduce database traffic,second-level cache keeps loaded objects at the Session Factorylevel between transactions. These objects are available to thewhole application, not just to the user running the query. Thisway, each time a query returns an object that is already loadedin the cache, one or more database transactions potentially areavoided.
  • 75. In addition, you can use a query-level cache if you need to cacheactual query results, rather than just persistent objects.Each cache provides different capacities in terms ofperformance, 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. JBossTreeCache is a powerful replicated (synchronous or asynchronous) and transactional cache. Use this solution if you really need a true transaction-capable caching architecture.
  • 76. Another cache implementation worth mentioning is thecommercial Tangosol Coherence cache.Caching StrategiesOnce you have chosen your cache implementation, you need tospecify your access strategies. The following four cachingstrategies 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 lazythen when the main object is created then it contains only arefernce to the object it contains. This reference is the proxy ofthe object it contains and this pattern is called proxy patters.
  • 77. 10) Interfaces in Hibernate:Configuration,Session,Transaction and SessionFactory11) Light weight ,Medium Weight and Heavy Weightmapping:There are four levels of Hibernate Quality:Pure: Stored ProceduresLight: JDBCMedium:Heavy:composition,inheritance, polymorphism,persistence by reachability12) Difference between Hibernate and Ibatis:In Ibatis Results of the SQL queries are mapped to the Objectswhere as in Hibernate the table is mapped to the object. Ibatiswould be faster as it making use of the queries directly and isuseful when you personally don’t have much knowledge aboutthe database.13) What is NHibernate?NHibernate is an Object Relational Mapping (ORM) solution for.Net.
  • 78. 14) Integrating Hibernate and Spring1) 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”> <beanclass=”org.springframework.jndi.JndiObjectFactoryBean”> <property name=”jndiName”><value>javax.transaction.TransactionManager</value> </property>
  • 79. </bean> </property></bean>2) Configure the DataSource in the ‘spring.xml’<beanid=“dataSource”class=“org.springframework.jdbc.datasource.DriverManagerDataSource”> <propertyname=“driverClassName”> <value>org.hsqldb.jdbcDriver</value> </property> <propertyname=“url”> <value>jdbc:hsqldb:mem:widgets</value> </property> <propertyname=“username”><value>sa</value></property> <propertyname=“password”><value></value></property></bean>
  • 80. Interceptors can be used in cases where wemay requiresome sort of callback methods called justbefore theactual operation is called. For example Ifit is requiredto log any perticular SQL in some differentlog/audit file,then we can set a simple Interceptor likeCaptureSQL orLogSQL, just while opening Sesson usingSessionFactoryopenSession (Interceptor) method.Following sample interceptor does thelogging of SQLon prepare statement. import org.apache.log4j.Logger;import org.hibernate.EmptyInterceptor;public class CaptureSQL extendsEmptyInterceptor { private static Logger log =Logger.getLogger("L1"); public String onPrepareStatement(Stringsql) { log.debug("Loging SQL statement...... start"); log.debug(sql);
  • 81. log.debug("Loging SQL statement...... end"); return sql; }}CaptureSQL is the user defined class thatextendsorg.hibernate.EmptyInterceptor to becomereceivingcallback overridden method, such as"onPrepareStatement", when ever a Sessionis opened,by calling SessionFactory.openSession(newCaptureSQL()).Appropriate log4j.properties file should beconfiguredto be able to handle these logging part. Mysample log4j.propertiesfile is as follows: log4j.rootLogger=DEBUGlog4j.logger.L1=INHERIT, Llog4j.appender.L=org.apache.log4j.FileAppen
  • 82. derlog4j.appender.L.file=sample.txtlog4j.appender.L.layout=org.apache.log4j.PatternLayoutlog4j.appender.L.layout.ConversionPattern=%d [%t] %C{1} - %m%nAnd the Client code is as follows:Client.java (Hibernate one to one mappingTest 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 finalSessionFactorysessionFactory; static { try { // Create the SessionFactory fromhibernate.cfg.xml
  • 83. sessionFactory = newConfiguration().configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log theexception, as it might be swallowedSystem.err.println("Initial SessionFactorycreation failed." + ex); throw newExceptionInInitializerError(ex); } } public staticSessionFactorygetSessionFactory() { return sessionFactory; } public static void createRecord() { Session session =getSessionFactory().openSession(newCaptureSQL()); 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);
  • 84. trx.commit(); session.close(); } /** * @paramargs */ public static void main(String[] args){ createRecord(); }}hibernate.cfg.xml (configuration file forcreation of Hibernate session factory)// This source is provided on "AS IS"basis.<?xml version=1.0 encoding=utf-8?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/HibernateConfiguration DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration><session-factory>
  • 85. <!-- Database connection settings --><property name="connection.driver_class"> org.hsqldb.jdbcDriver</property><property name="connection.url"> jdbc:hsqldb:hsql://localhost/</property><propertyname="connection.username">sa</property><propertyname="connection.password"></property><!-- JDBC connection pool (use the built-in) --><propertyname="connection.pool_size">1</property><!-- SQL dialect --><property name="dialect"> org.hibernate.dialect.HSQLDialect </property><!-- Enable Hibernates automatic sessioncontext management --><propertyname="current_session_context_class"> thread </property> <!-- Echo all executed SQL tostdout -->
  • 86. <property name="show_sql">true</property><mapping resource="car.hbm.xml"/></session-factory></hibernate-configuration>This example domain class "Car.java" fileis 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() { return model; } public void setModel(String model) { this.model = model;
  • 87. } public String getSegment() { return segment; } public void setSegment(String segment) { this.segment = segment; }}And the corresponding Hibernate HBMconfiguration file is as follows:// This source is provided on "AS IS"basis.<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD3.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"/> <property name="segment"column="car_segment"/></class></hibernate-mapping>
  • 88. In order to execute this example, you mayhave to create relevant table(the DDL as shown below) or use appropriateconfiguration entry forcreation of database table at runtime.// This source is provided on "AS IS"basis.create table car(car_namevarchar(20), car_modelvarchar(50),car_segmentvarchar(50), primary key(car_name));On executing Client code, we can see logsare getting writtenonto the sample.txt log file, as shownfollows: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 beforeonPrepareStatement:<<The DML used in this operation on theSession opened withCatureSQL as interceptor>>2009-01-04 09:01:11,593 [main] CaptureSQL -Loging SQL statement .end
  • 89. There are many other interesting callbackmethodscan be used from EmptyInterceptor, such asfindDirty-> to check where the Entity inuse is dirty or not.->if this method returns an empty int[]array, thenthe Entity object supplied in argument ofthismethod is not dirty.->if this method returns an empty int[]array, thenthe Entity object is dirty or is updated bysome otherprocess in database.->by returning a null from the overriddenfindDirty methodone can opt for using Hibernates own ordefault dirtychecking mechanism.onLoad-> it is called just before Entityobject is initialized.onDelete-> it is called just before Entityobject is deleted.
  • 90. and many more callback methods as definedinorg.hibernate.Intercept interface.Hibernate Question on Interceptor 2:Can there be any Interceptor forSessionFactory, so thatit can be used across all the Session fromthis SessionFactory?Yes, there can be an Interceptor defined inorg.hibernate.cfg.Configurationto be defined during SessionFactorycreation.Configuration.setInterceptor method can beused for this purpose.Hibernate Question on Interceptor 3:Can one be able to use Hibernate Sessionfrom within the callbackmethods of Interceptor?No, Session may not be used from thecallback methods of Interceptor.Hibernate Question on Interceptor 4:Can the collection be recreated/initializedlazily while executing anycallback method from Interceptor?
  • 91. No, Collection may not be lazilyinitialized, from callback methodof Interceptors.Interceptors in Hibernate Framework can beof two different scopes,such as session scoped and session factoryscoped.In this example and above code isimplemented using Hibernate sesssionscoped interceptors in mind.In the following section we shall re-createthis example usingHibernate session factory scopedinterceptor.Just you have to do is to change the staticinitializer block in the Clientprogram, and set appropriate interceptorinstance into the Configurationinstance, and use this interceptor whilebuilding Hibernate session factory.And of course you may open session with nointerceptor instance passed asconstructor argument in the createRecordmethod.
  • 92. Code snippet as shown below:// This source is provided on "AS IS"basis. static { try { // Create the SessionFactory fromhibernate.cfg.xmlsessionFactory = newConfiguration().setInterceptor(newCaptureSQL()).configure().buildSessionFactory(); } catch (Throwable ex) { // Make sure you log theexception, as it might be swallowedSystem.err.println("Initial SessionFactorycreation failed." + ex); throw newExceptionInInitializerError(ex); } }If you like to share yourcomment/suggestions/feedback relating tothis Page,you can do so by droping us an email atusingframeworks @ gmail . com
  • 93. with the subject line mentioning URL forthis Page (i.e, /Hibernate-Interceptor-example.php) or use thisLINK.As per this websites privacy policy, wenever disclose your email id,though we shall post yourcomments/suggestions/feedback withyour name (optional) and date on this Page.If you dont want yourcomments/suggestions/feedback to be sharedin this Page, pleasemention so in your email to us. Thank youvery much.....If anything missed out , please let me knowattechienjoy at yahoo . com