ty.bsc.it java qb u6

10
QUESTION BANK UNIT –VI Q.1 Explain the Hibernate Framework Ans: Hibernate is an Object-relational mapping (ORM) tool. Object-relational mapping or ORM is a programming method for mapping the objects to the relational model where entities/classes are mapped to tables, instances are mapped to rows and attributes of instances are mapped to columns of table. A “virtual object database” is created that can be used from within the programming language. Hibernate is a persistence framework which is used to persist data from Java environment to database. Persistence is a process of storing the data to some permanent medium and retrieving it back at any point of time even after the application that had created the data ended. The above diagram shows a comprehensive architecture of Hibernate. In order to persist data to a database, Hibernate create an instance of entity class(Java class mapped with database table). This object is called Transient object as they are not yet associated with the session or not yet persisted to a database. To persist the object to database, the instance of SessionFactory interface is created. SessionFactory is a singleton instance which implements Factory design pattern. SessionFactory loads hibernate.cfg.xml file(Hibernate configuration file. More details in following section) and with the help of TransactionFactory and ConnectionProvider implements all the configuration settings on a database. Each database connection in Hibernate is created by creating an instance of Session interface. Session represents a single connection with database.Session objects are created from SessionFactory object. Hibernate also provides built-in Transaction APIs which abstracts away the application from underlying JDBC or JTA transaction. Each transaction represents a single atomic unit of work. One Session can span through multiple transactions. SessionFactory (org.hibernate.SessionFactory) A thread-safe, immutable cache of compiled mappings for a single database. A factory for

Upload: lokesh-singrol

Post on 12-Apr-2017

17 views

Category:

Education


0 download

TRANSCRIPT

Page 1: TY.BSc.IT Java QB U6

QUESTION BANK

UNIT –VI

Q.1 Explain the Hibernate FrameworkAns:

Hibernate is an Object-relational mapping (ORM) tool. Object-relational mapping or ORM is a programming method for mapping the objects to the relational model where entities/classes are mapped to tables, instances are mapped to rows and attributes of instances are mapped to columns of table.

A “virtual object database” is created that can be used from within the programming language. Hibernate is a persistence framework which is used to persist data from Java environment to database.

Persistence is a process of storing the data to some permanent medium and retrieving it back at any point of time even after the application that had created the data ended.

The above diagram shows a comprehensive architecture of Hibernate. In order to persist data to a database, Hibernate create an instance of entity class(Java class mapped with database table). This object is called Transient object as they are not yet associated with the session or not yet persisted to a database.

To persist the object to database, the instance of SessionFactory interface is created. SessionFactory is a singleton instance which implements Factory design pattern. SessionFactory loads hibernate.cfg.xml file(Hibernate configuration file. More details in following section) and with the help of TransactionFactory and ConnectionProvider implements all the configuration settings on a database.

Each database connection in Hibernate is created by creating an instance of Session interface. Session represents a single connection with database.Session objects are created from SessionFactory object.

Hibernate also provides built-in Transaction APIs which abstracts away the application from underlying JDBC or JTA transaction. Each transaction represents a single atomic unit of work. One Session can span through multiple transactions.

SessionFactory (org.hibernate.SessionFactory)A thread-safe, immutable cache of compiled mappings for a single database. A factory for org.hibernate.Session instances. A client of org.hibernate.connection.ConnectionProvider. Optionally maintains a second level cache of data that is reusable between transactions at a process or cluster level.Session (org.hibernate.Session)A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC java.sql.Connection. Factory for org.hibernate.Transaction. Maintains a first level cache of persistent the application’s persistent objects and collections; this cache is used when navigating the object graph or looking up objects by identifier.Persistent objects and collections

Page 2: TY.BSc.IT Java QB U6

Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one org.hibernate.Session. Once the org.hibernate.Session is closed, they will be detached and free to use in any application layer (for example, directly as data transfer objects to and from presentation).Transient and detached objects and collectionsInstances of persistent classes that are not currently associated with a org.hibernate.Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session.Transaction (org.hibernate.Transaction)(Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A org.hibernate. Session might span several org.hibernate.Transactions in some cases. However, transaction demarcation, either using the underlying API or org.hibernate.Transaction, isnever optional. ConnectionProvider (org.hibernate.connection.ConnectionProvider)(Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer. TransactionFactory (org.hibernate.TransactionFactory)(Optional) A factory for org.hibernate.Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer.

Q.2 Explain the Struts FrameworkAns: The Struts Framework is a standard for developing well-architected Web applications. It has the following

features: Open source Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three levels:

o Model: application state o View: presentation of data (JSP, HTML) o Controller: routing of the application flow

Implements the JSP Model 2 Architecture Stores application routing information and request mapping in a single core file, struts-config.xml

The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the developer.

All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration file struts-config.xml is used by the controller to determine the routing of the flow. This flows consists of an alternation between two transitions:

Page 3: TY.BSc.IT Java QB U6

From View to Action:A user clicks on a link or submits a form on an HTML or JSP page. The controller receives the request, looks up the mapping for this request, and forwards it to an action. The action in turn calls a Model layerFrom Action to View:(Business layer) service or function. After the call to an underlying function or service returns to the action class, the action forwards to a resource in the View layer and a page is displayed in a web browser.

The diagram below describes the flow in more detail:1. User clicks on a link in an HTML page.2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and routes to an action.3. Action makes a call to a Model layer service.4. Service makes a call to the Data layer (database) and the requested data is returned.5. Service returns to the action.6. Action forwards to a View resource (JSP page)7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP page.8. JSP file is invoked and sent to the browser as HTML.9. User is presented with a new HTML page in a web browser.

Q.3 Explain web.xml and struts.xml filesAns: The interactions in MVC model between Model, View and Controller flow are taken care by the struts

configuration files. These files are web.xml, struts.xml, struts-config.xml and struts.properties.web.xml:

The web.xml configuration file is a J2EE configuration file that determines how elements of the HTTP request are processed by the servlet container.

The web.xml web application descriptor file represents the core of the Java web application, so it is appropriate that it is also part of the core of the Struts framework.

In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts framework and handles all requests.

This filter can contain initialization parameters that affect what, if any, additional configuration files are loaded and how the framework should behave.

The web.xml file needs to be created under the folderWebContent/WEB-INF. Configuring web.xml for the framework is a matter of adding a filter and filter-mapping.

struts.xml The struts.xml file contains the configuration information that you will be modifying as actions are

Page 4: TY.BSc.IT Java QB U6

developed. This file can be used to override default settings for an application, for example struts.devMode =

false and other settings which are defined in property file. This file can be created under the folder WEB-INF/classes.

Example:<struts><constant name="struts.devMode" value="true" /><package name="helloworld" extends="struts-default"><action name="hello"class="HelloWorldAction" method="execute"><result name="success">/HelloWorld.jsp</result></action></package></struts>

Q.4 What is object relational mapping(ORM)? what are its advantages?Ans: 1. Facilitates implementing the Domain Model pattern: This one reason supersedes all others. In short

using this pattern means that you model entities based on real business concepts rather than based on your database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model.

2. Huge reduction in code: ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.

3. Changes to the object model are made in one place: One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.

4. Rich query capability: ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.

5. Navigation: You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a PO and you want to access it's Customer, you can simply access PO. Customer and the ORM will take care of loading the data for you without any effort on your part.

6. Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of POs without any of its child / related objects, while in other scenarios you can specify to load a PO, with all its child Line Items, etc.

7. Concurrency support: Support for multiple users updating the same data simultaneously.8. Cache management: Entities are cached in memory thereby reducing load on the database.9. Transaction management and Isolation: All object changes occur scoped to a transaction. The entire

transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.

10. Key Management: Identifiers and surrogate keys are automatically propogated and managed.Q.5 What is the importance of hibernate mapping file? Explain with suitable exampleAns: Mapping file is the heart of hibernate application.

Every ORM tool needs this mapping, mapping is the mechanism of placing an object properties into column’s of a table.

Mapping can be given to an ORM tool either in the form of an XML or in the form of the annotations. The mapping file contains mapping from a pojo class name to a table name and pojo class variable

names to table column names. While writing an hibernate application, we can construct one or more mapping files, mean a hibernate

application can contain any number of mapping files. generally an object contains 3 properties like

Identity (Object Name)

Page 5: TY.BSc.IT Java QB U6

State (Object values) Behavior (Object Methods)

Example:<hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class></hibernate-mapping>

Q.6 Explain the working of HibernateAns: Hibernate is the ORM tool given to transfer the data between a java (object) application and a database

(Relational) in the form of the objects. Hibernate is the open source light weight tool given by Gavin King

Hibernate provides a solution to map database tables to a class. It copies one row of the database data to a class. In the other direction it supports to save objects to the database. In this process the object is transformed to one or more tables.

Q.7. Write a sample hibernate configuration file? Explain the elements of the file

Page 6: TY.BSc.IT Java QB U6

Ans: Configuration is the file loaded into an hibernate application when working with hibernate, this configuration file contains 3 types of information.

Connection Properties Hibernate Properties Mapping file name(s)

<hibernate-configuration> : This is next and parent tag for the hibernate configuration. It is the base tag, containg all the hibernate configuration setting in its sub tags.

<session-factory> : This is sub tag of <hibernate-configuration> that hold all the required properties to communicate with the database, like database connection setting url, usernate, password and etc.

<property name = “---“>---</property> : This is the sub tag of <session-factory>, which describe all the required properties in order to communicate with the database like connection properties for database.

Q.8 Explain Filter Dispatcher and any two action components used by strutsAns: A Filter Dispatcher is used as the Controller in Struts.

Its name in packaged Structure is org.apache.struts2.dispatcher.FilterDispatcher. Prior to using it in the application, it has to be registered in the web.xml as below. At first the FilterDispatcher verifies the request URI and determines the right action for it. The mappings of URI’s and the action classes are present in the struts.xml file found in the

WEB-INF/classes directory.FilterDispatcher does the following for eact action invocation.1)Determines which action to invoke for a requested URI by consulting the Configuration manager2) Interceptors registered for the action are invoked one after the other.3) Then the action method is executed.4) Then the Filter Dispatcher executes the Result.

Optionally you can extend the ActionSupport class which implements six interfaces including Actioninterface. The Action interface is as follows:public interface Action {

Page 7: TY.BSc.IT Java QB U6

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 Explain in brief MVC architecture with the help of suitable diagramAns: Model-View-Controller architecture is used for interactive web-applications. This model minimizes

the coupling between business logic and data presentation to web user. This model divides the web based application into three layers:

Model: Model domain contains the business logics and functions that manipulate the business data. It provides updated information to view domain and also gives response to query. And the controller can access the functionality which is encapsulated in the model.

View: View is responsible for presentation aspect of application according to the model data and also responsible to forward query response to the controller.

Controller: Controller accepts and intercepts user requests and controls the business Objects to fulfill these requests. An application has one controller for related

functionality. Controller can also be depends on the type of clients.

Q.10 Write a short note on Interceptors in strutsInterceptors allow for crosscutting functionality to be implemented separately from the action as well as the framework. You can achieve the following using interceptors:

Providing preprocessing logic before the action is called. Providing postprocessing logic after the action is called. Catching exceptions so that alternate processing can be performed. Many of the features provided in the Struts2 framework are implemented using interceptors; examples

Page 8: TY.BSc.IT Java QB U6

include exception handling, file uploading, lifecycle callbacks and validation etc.

Q.11 Explain the different roles of Action in struts framework Actions are the core of the Struts2 framework, as they are for any MVC (Model View Controller)

framework. Each URL is mapped to a specific action, which provides the processing logic necessary to service the request from the user.

But the action also serves in two other important capacities. First, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result. Second, the action must assist the framework in determining which result should render the view that will be returned in the response to the request.

Q.12 What is value-stack? What are the different type of object it can hold off? Explain their accessing strategies?What is OGNL ?

The value stack is a set of several objects which keeps the following objects in the provided order:

SN Objects & Description

1

Temporary ObjectsThere are various temporary objects which are created during execution of a page. For example the current iteration value for a collection being looped over in a JSP tag.

2The Model ObjectIf you are using model objects in your struts application, the current model object is placed before the action on the value stack

3 The Action ObjectThis will be the current action object which is being executed.

4Named ObjectsThese objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes

OGNL:The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion.

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 the pound symbol.

As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The ActionContext map consists of the following:

application - application scoped variablessession - session scoped variablesroot / value stack - all your action variables are stored hererequest - request scoped variablesparameters - request parametersatributes - the attributes stored in page, request, session and application scope

Page 9: TY.BSc.IT Java QB U6

It is important to understand that the Action object is always available in the value stack. So, therefore if your Action object has properties x and y there are readily available for you to use.