1. QUESTION BANK
UNIT –VI
Q.1 Explainthe Hibernate Framework
Ans:
Hibernateis an Object-relationalmapping (ORM)tool.Object-relationalmappingorORMis a
programming method formapping theobjectsto the relational modelwhereentities/classesare mapped
to tables,instancesaremapped to rowsand attributesof instancesaremapped to columnsof table.
A “virtual objectdatabase”iscreated thatcan be used fromwithin the programming language.
Hibernateis a persistenceframeworkwhich isused to persist data fromJava environmentto database.
Persistenceis a processof storing the data to some permanentmediumand retrieving it backat any
pointof time even afterthe application thathad created thedata ended.
The abovediagramshowsa comprehensivearchitectureof Hibernate.In orderto persistdatato a
database,Hibernatecreatean instanceof entity class(Java classmapped with databasetable). This
objectis called Transient objectasthey arenot yet associated with thesession or notyet persisted to a
database.
To persist theobjectto database,theinstanceof SessionFactory interfaceiscreated.SessionFactory isa
singleton instancewhich implements Factory design pattern.SessionFactory loadshibernate.cfg.xml
file(Hibernateconfiguration file.Moredetails in following section) and with the help of
TransactionFactory and ConnectionProviderimplementsallthe configuration settingson a database.
Each databaseconnection in Hibernateis created by creating an instanceof Session interface.Session
representsa single connection with database.Session objectsarecreated fromSessionFactory object.
Hibernatealso providesbuilt-in Transaction APIswhich abstractsaway the application fromunderlying
JDBC or JTA transaction.Each transaction representsa singleatomic unitof work.OneSession can span
through multipletransactions.
SessionFactory(org.hibernate.SessionFactory)
A thread-safe,immutablecacheof compiled mappingsfora single database. A factory fororg.hibernate.Session
instances.A client of org.hibernate.connection.ConnectionProvider.Optionally maintainsa second levelcache of
datathatis reusable between transactions ata processor cluster level.
Session(org.hibernate.Session)
A single-threaded,short-lived objectrepresenting a conversationbetween the application and thepersistent
store.Wrapsa JDBC java.sql.Connection. Factory fororg.hibernate.Transaction.Maintainsa firstlevel cacheof
persistentthe application’spersistentobjectsand collections;thiscache is used when navigating theobject
graph orlooking up objectsby identifier.
2. Persistent objectsand collections
Short-lived,singlethreaded objects containing persistentstateand businessfunction.Thesecan beordinary
JavaBeans/POJOs.They areassociated with exactly oneorg.hibernate.Session.Oncetheorg.hibernate.Session is
closed, they will bedetached and free to use in any application layer (forexample, directly as datatransfer
objectsto and frompresentation).
Transient anddetached objects andcollections
Instancesof persistentclassesthatare notcurrently associated with a org.hibernate.Session.They may have
been instantiated by the application and notyet persisted,orthey may havebeen instantiated by a closed
org.hibernate.Session.
Transaction(org.hibernate.Transaction)
(Optional) A single-threaded,short-lived objectused by theapplication to specify atomicunits of work.It
abstractstheapplication fromthe underlying JDBC,JTA or CORBA transaction.A org.hibernate. Session might
span severalorg.hibernate.Transactionsin somecases.However,transaction demarcation,eitherusing the
underlying APIororg.hibernate.Transaction,is
neveroptional.
ConnectionProvider(org.hibernate.connection.ConnectionProvider)
(Optional) A factory for,and poolof,JDBCconnections.Itabstractsthe application fromunderlying
javax.sql.DataSourceorjava.sql.DriverManager. Itisnotexposed to application,butit can be extended and/or
implemented by the developer.
TransactionFactory(org.hibernate.TransactionFactory)
(Optional) A factory fororg.hibernate.Transaction instances.Itisnot exposed to theapplication, butit can be
extended and/orimplemented by the developer.
Q.2 Explainthe Struts Framework
Ans: The StrutsFrameworkisa standard fordeveloping well-architected Web applications.Ithasthe following
features:
Open source
Based on the Model-View-Controller(MVC) design paradigm,distinctly separating allthreelevels:
o Model: application state
o View: presentation of data (JSP,HTML)
o Controller:routing of theapplication flow
ImplementstheJSPModel 2 Architecture
Storesapplication routing information and requestmappingin a single core file, struts-config.xml
The StrutsFramework,itself,only fills in theView and Controllerlayers. The Modellayer is left to the developer.
All incoming requestsareintercepted by the Strutsservlet controller.The StrutsConfiguration filestruts-
3. config.xmlisused by the controllerto determine therouting of the flow.This flowsconsistsof an alternation
between two transitions:
From Viewto Action:
A userclicks on a link orsubmitsa formon an HTML or JSPpage.The controller receives the request, looksup the
mapping forthisrequest,and forwardsitto an action.The action in turn calls a Modellayer
From Actionto View:
(Businesslayer) service or function.Afterthecall to an underlying function orservicereturnsto the action class,
the action forwardsto a resource in the View layer and a pageis displayed in a web browser.
The diagrambelowdescribes the flowin more detail:
1. User clicks on a link in an HTML page.
2. Servlet controller receives therequest,looksup mapping information in struts-config.xml,and
routesto an action.
3. Action makesa call to a Modellayer service.
4. Service makesa call to the Datalayer (database)and therequested data isreturned.
5. Service returnsto theaction.
6. Action forwardsto a View resource(JSPpage)
7. Servlet looksup the mapping fortherequested resourceand forwards to theappropriateJSP
page.
8. JSP file is invoked and sentto the browserasHTML.
9. User is presented witha newHTML pagein a web browser.
Q.3 Explainweb.xml and struts.xml files
Ans: The interactions in MVCmodel between Model,View and Controllerflow are taken care by the struts
configuration files.Thesefiles are web.xml,struts.xml,struts-config.xmland struts.properties.
web.xml:
The web.xmlconfiguration fileis a J2EE configuration filethatdetermines how elementsof the HTTP
requestare processed by the servlet container.
The web.xml web application descriptor file represents the core of the Java web application, so it is
appropriatethatit is also partof the core of the Strutsframework.
In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts
frameworkand handlesallrequests.
This filter can contain initialization parameters that affect what, if any, additional configuration files are
loaded and howtheframeworkshould behave.
The web.xmlfile needsto be created underthefolderWebContent/WEB-INF.
Configuring web.xmlfortheframeworkisa matterof adding a filter and filter-mapping.
4. struts.xml
The struts.xml file contains the configuration information that you will be modifying as actions are
developed.
This file can be used to override default settings for an application, for example struts.devMode =
falseand other settingswhich are defined in property file.
This file can be created underthe folder WEB-INF/classes.
Example:
<struts>
<constantname="struts.devMode"value="true"/>
<packagename="helloworld"extends="struts-default">
<action name="hello"class="HelloWorldAction" method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
Q.4 What is objectrelational mapping(ORM)?what are its advantages?
Ans: 1. FacilitatesimplementingtheDomainModel pattern: This onereason supersedesall others.In short
using this pattern meansthatyou modelentities based on real businessconceptsratherthan based on
yourdatabasestructure.ORMtoolsprovidethisfunctionality through mapping between thelogical
businessmodeland the physicalstoragemodel.
2. Huge reduction incode: ORM toolsprovidea hostof services thereby allowing developersto focuson the
businesslogic of the application rather than repetitive CRUD(CreateRead UpdateDelete) logic.
3. Changesto the object model are made in one place:One you updateyourobjectdefinitions,theORM
will automatically usethe updated structurefor retrievalsand updates.Thereare no SQL Update,Delete
and Insertstatementsstrewn throughoutdifferentlayersof theapplication thatneed modification.
4. Rich query capability:ORMtoolsprovidean objectoriented query language.Thisallowsapplication
developersto focuson the objectmodel and notto haveto be concerned with thedatabasestructureor
SQL semantics.TheORM tool itself will translatethequery languageinto the appropriatesyntax forthe
database.
5. Navigation:You can navigateobjectrelationshipstransparently.Related objectsareautomatically
loaded asneeded.For exampleif you load a POand you wantto accessit's Customer,you can simply
access PO. Customerand theORMwill take care of loading thedata for you without any efforton your
part.
6. Data loadsare completelyconfigurableallowingyoutoloadthe data appropriatefor each scenario.
For examplein onescenario you mightwantto load a list of POswithoutany of its child / related objects,
while in other scenariosyou can specify to load a PO,with all its child Line Items,etc.
7. Concurrencysupport: Supportformultipleusers updating thesamedata simultaneously.
8. Cache management:Entities are cached in memory thereby reducing load on the database.
9. Transactionmanagementand Isolation:Allobjectchangesoccurscoped to a transaction.Theentire
transaction can either be committed orrolled back. Multipletransactionscan be activein memory in the
sametime, and each transactionschangesareisolated formon another.
10. Key Management: Identifiersand surrogatekeysareautomatically propogated and managed.
Q.5 What is the importance of hibernate mapping file?Explainwith suitable example
Ans: Mapping fileis the heartof hibernateapplication.
Every ORMtool needsthis mapping,mappingisthe mechanismof placing an objectpropertiesinto
column’sof a table.
Mapping can begiven to an ORMtool either in the formof an XMLor in theformof theannotations.
The mapping file contains mapping froma pojo classnameto a table nameand pojo classvariable
namesto table column names.
While writing an hibernateapplication,wecan construct oneor more mapping files,mean a hibernate
application can contain any numberof mapping files.
5. generally an objectcontains 3 properties like
Identity (ObjectName)
State(Objectvalues)
Behavior(ObjectMethods)
Example:
<hibernate-mapping>
<class name="Employee"table="EMPLOYEE">
<meta attribute="class-description">Thisclass
containstheemployeedetail.
</meta>
<id name="id"type="int"column="id">
<generatorclass="native"/>
</id>
<propertyname="firstName"column="first_name"
type="string"/>
<propertyname="lastName"column="last_name"
type="string"/>
<propertyname="salary"column="salary"type="int"/>
</class>
</hibernate-mapping>
Q.6 Explainthe working of Hibernate
Ans: Hibernateis the ORMtool given to transferthedata between a java (object) application and a database
(Relational) in theformof the objects. Hibernate is the open sourcelight weighttool given by GavinKing
Hibernateprovidesa solution to map databasetablesto a class. It copiesone row of the databasedatato a
class.In the otherdirection it supportsto saveobjectsto thedatabase.In thisprocess the objectis transformed
to oneor more tables.
Q.7. Write a sample hibernate configurationfile?Explainthe elementsofthe file
6. Ans: Configuration isthefile loaded into an hibernateapplication when working with hibernate,thisconfiguration file
contains 3 typesof information.
Connection Properties
HibernateProperties
Mapping filename(s)
<hibernate-configuration>:This is nextand parenttag for thehibernateconfiguration.Itis thebasetag,
containg all the hibernateconfiguration setting in its sub tags.
<session-factory>: This is sub tag of <hibernate-configuration>thathold all the required propertiesto
communicatewiththe database,likedatabaseconnection setting url,usernate,password and etc.
<property name = “---“>---</property>:This is the sub tag of <session-factory>,which describeall the
required propertiesin orderto communicatewith thedatabaselike connection propertiesfordatabase.
Q.8 ExplainFilterDispatcher and any two action componentsused by struts
Ans: A Filter Dispatcheris used as the Controllerin Struts.
Its namein packaged Structureisorg.apache.struts2.dispatcher.FilterDispatcher.
Prior to using it in the application,it hasto be registered in theweb.xmlasbelow.
At first theFilterDispatcher verifies therequest URIand determinesthe rightaction forit.
The mappingsof URI’sand theaction classes are presentin the struts.xmlfilefound in theWEB-
INF/classesdirectory.
FilterDispatcherdoes the followingforeact actioninvocation.
1)Determineswhich action to invokefora requested URIby consulting theConfiguration manager
2) Interceptorsregistered forthe action areinvoked oneafter theother.
3) Then the action method is executed.
4) Then the Filter Dispatcherexecutesthe Result.
Optionally you can extend the ActionSupportclasswhich implementssix interfaces including Actioninterface.The
Action interface is as follows:
public interface Action {
7. public static final String SUCCESS = "success";
public static final String NONE = "none";
public static final String ERROR = "error";
public static final String INPUT = "input";
public static final String LOGIN = "login";
public String execute() throws Exception;
}
Q.9 Explainin briefMVC architecture with the helpof suitable diagram
Ans: Model-View-Controllerarchitectureis used for interactiveweb-applications.Thismodelminimizes
the coupling between businesslogicand data presentation to web user.This model dividesthe web based
application into three layers:
Model:Model domain containsthebusinesslogicsand functionsthatmanipulatethe
businessdata.Itprovidesupdated information to view domain and also gives
responseto query.And thecontroller can accessthe functionality which is
encapsulated in themodel.
View: Viewis responsibleforpresentation aspectof application according to themodel
dataand also responsibleto forward query responseto thecontroller.
Controller:Controlleraccepts and interceptsuser requestsand controlsthebusiness
Objectsto fulfill these requests.An application hasonecontrollerfor related
functionality.Controllercan also be dependson thetype of clients.
Q.10 Write a short note on Interceptors instruts
Interceptorsallowforcrosscutting functionality to beimplemented separately fromthe action aswell as the
framework.You can achievethe following using interceptors:
Providing preprocessing logicbeforetheaction is called.
Providing postprocessinglogicafterthe action is called.
Catching exceptionsso thatalternateprocessing can be performed.
Many of the featuresprovided in the Struts2frameworkareimplemented using interceptors;examples
8. include exception handling,fileuploading,lifecyclecallbacksand validation etc.
Q.11 Explainthe differentrolesof Action in struts framework
Actionsare the core of the Struts2framework,asthey arefor any MVC(ModelView Controller)
framework.Each URLis mapped to a specific action,which providesthe processing logicnecessary to
service the requestfromthe user.
But the action also serves in two otherimportantcapacities.First, the action playsan importantrole in
the transferof datafromtherequestthrough to the view,whetherits a JSP orother typeof result.
Second,theaction must assistthe frameworkin determining which result should rendertheview that
will be returned in the responseto the request.
Q.12 What is value-stack?Whatare the differenttype of objectit can holdoff? Explaintheir accessing
strategies?WhatisOGNL ?
The valuestack is a set of several objects which keepsthe following objectsin the provided order:
SN Objects & Description
1
Temporary Objects
There are varioustemporary objectswhich arecreated during execution of a
page.Forexamplethe currentiteration valuefor a collection being looped
overin a JSPtag.
2
The Model Object
If you are using model objectsin yourstrutsapplication,thecurrentmodel
objectis placed beforetheaction on the valuestack
3
The ActionObject
This will be the currentaction objectwhich is being executed.
4
NamedObjects
These objectsinclude#application,#session,#request,#attr and #parameters
and refer to thecorresponding servletscopes
OGNL:
The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and
manipulatedataon theValueStack.OGNLalso helps in data transferand typeconversion.
The OGNL is very similar to the JSP Expression Language. OGNL is based on the idea of having a root or default
object within the context. The properties of the default or root object can be referenced using the markup
notation,which is thepound symbol.
As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The
ActionContextmap consistsof thefollowing:
application - application scoped variables
session- session scoped variables
root / valuestack - all youraction variablesare stored here
request - requestscoped variables
parameters - requestparameters
atributes- the attributesstored in page,request,session and application scope
It is important to understand that the Action object is always available in the value stack. So, therefore if your