Saturday, July 5, 2008

Hibernate Vs. iBatis?

Hibernate Vs. iBatis?
Hibernate or iBatis or both ? Which is better?
Which one to use and when?

These are the few questions that continuously get asked in most of forums.
What’s really difference between two and really more importantly when should I use one over the other. Its pretty interesting question because there are major differences between iBatis and Hibernate.

Within in the java persistence there is no one size, fits all solution. So, in this case Hibernate which is a de facto standard is used in lot of places.

Let us consider a scenario where Hibernate work great for initial model. Now Suddenly if you are using stored procedures, well we can do it in Hibernate but its little difficult; ok we map those, all of sudden we got some reporting type of queries, those don’t have keys have group bys; with some difficulty here we can use name queries and stuff like that, but now starts getting more complicated, we have complex joins, yes you can do in hibernate, but we can’t do with average developer. We have sql that just doesn’t work.

So these are some of the complexities. One of the other things I find is, if am looking at an application that doesn’t work very well with an ORM, aside from these considerations of using stored procedures, already using SQL, complex joins. In other words, Hibernate works very well if your data model is well in sync with object model, because ORM solutions like Hibernate map object to tables. However, let’s suppose data model is not in sync with object model, in this case you have do lot of additional coding and complexities are entering into your application, start coming the beyond the benefits of ORM. So, again all of sudden you are noticing that the flow is gone; our application is becoming very very complex and developers can’t maintain the code.

This is where the model starts breaking down. One size does not fit all. So this is where I like to use iBatis; as the alternative solution for these type of situations, iBatis maps results sets to objects, so no need to care about table structures. This works very well for stored procedures, works very well for reporting applications, etc,.

Now the question is , does it work well for simple CRUD applications? Well, it works because what we have to write is sql. Then why not use Hibernate for that?

You can start see Some of the decision criteria that comes into play. So one of the other follow on questions that typically get is , can I use both? That’s really interesting question! because the answer is sure.

But,such a thing will never ever exists is java persistence world. However we can kind of use both to create this little hybrid. So think of this kind scenario, we have very large application where Hibernate is working very well for it, but we have a reporting piece that just is a real nag , its query only , so we can do is, we can use iBatis to pull up the queries for reporting piece and still use Hibernate for all the operational stuff and updates. This model actually works well, it doesn’t break the transactional model, and it doesn’t affect any of the primary & secondary caches with a Hibernate. It’s a good solution.

* Use iBatis if
o You want to create your own SQL's and are willing to maintain them
o your environment is driven by relational data model
o you have to work existing and complex schema's
* Use Hibernate if
o your environment is driven by object model and wants generates SQL automatically


The message is,

* One size does not fit all the java persistence and the important to know there are other solutions besides the traditional ORMs, and that would be iBatis.
* Both the solutions work well, given their specific domain.
* Look for the opportunity where you can use both.

What is iBatis ?

* A JDBC Framework
o Developers write SQL, iBATIS executes it using JDBC.
o No more try/catch/finally/try/catch.
* An SQL Mapper
o Automatically maps object properties to prepared statement parameters.
o Automatically maps result sets to objects.
o Support for getting rid of N+1 queries.
* A Transaction Manager
o iBATIS will provide transaction management for database operations if no other transaction manager is available.
o iBATIS will use external transaction management (Spring, EJB CMT, etc.) if available.
* Great integration with Spring, but can also be used without Spring (the Spring folks were early supporters of iBATIS).


What isn’t iBATIS ?

* An ORM
o Does not generate SQL
o Does not have a proprietary query language
o Does not know about object identity
o Does not transparently persist objects
o Does not build an object cache

Essentially, iBatis is a very lightweight persistence solution that gives you most of the semantics of an O/R Mapping toolkit, without all the drama. In other words ,iBATIS strives to ease the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.

XML Questions 2

16.What is the relevance of ElementFormDefault attribute in the Schema?

ElementFormDefault indicates whether or not locally declared elements must be qualified by the target namespace in an instance document. ElementFormDefault attribute in the Schema has the following relevance:

* Qualified: Each and every element of the Schema must be qualified with the namespace in the instance document.
* Unqualified: means only globally declared elements must be qualified with there namespace and not the local elements.


17.What is XML parser?

An XML parser is a piece of software which can do following:

* Check for well-formedness
* Validate the document
* Allows us to read, create or modify existing XML documents

Note: Parser is piece of software provided by vendors. An XML parser is built in Java runtime from JDK 1.4 onwards


18.What is DOM?

The Document Object Model (DOM) is a platform and language-independent standard object model for representing XML and related formats. DOM is standard API which is not specific to any programming language. DOM represents an XML document as a tree model. The tree model makes the XML document hierarchal by nature. Each and every construct of the XML document is represented as a node in the tree.


19.What is SAX?

SAX-Simple API for XML processing. SAX provides a mechanism for reading data from an XML document. It is a popular alternative to the Document Object Model (DOM).SAX provides an event based processing approach unlike DOM which is tree based.


20.What are the interfaces of SAX?

The interfaces of SAX are:

  • DocumentHandler- is used for getting event notification relating to a document.
  • DTDHandler- is implemented to get the notifications related to declarations in DTD like entities and notations
  • EntityResolver- is used for reading external entities.
  • ErrorHandler- is used for handling error related notifications.

21.What is the difference between SAX parser and DOM parser?

SAX DOM
A SAX parser takes the occurrences of components of an input document as events (i.e., event based processing), and tells the client what it reads as it reads through the input document. A DOM parser creates a tree structure in memory from an input document and then waits for requests from client.
No navigation possible (top to bottom only once) Whereas, we can navigate the DOM tree in any direction, any no. of times.
We cannot modify the document content in SAX We can modify the document content in DOM
A SAX parser serves the client application always only with pieces of the document at any given time. A DOM parser always serves the client application with the entire document no matter how much is actually needed by the client.
A SAX parser, however, is much more space efficient in case of a big input document A DOM parser is space inefficient when the document is huge.

Use SAX parser when

  • Input document is too big for available memory.
  • When only a part of the document is to be read and we create the data structures of our own.
  • If you use SAX, you are using much less memory and performing much less dynamic memory allocation.

Use DOM when

  • Your application has to access various parts of the document and using your own structure is just as complicated as the DOM tree.
  • Your application has to change the tree very frequently and data has to be stored for a significant amount of time.

22.What is a CDATA section in XML?

CDATA Sections are used to escape blocks of text containing characters which would otherwise be recognized as markup. All tags and entity references are ignored by an XML processor that treats them just like any character data. CDATA blocks have been provided as a convenience measure when you want to include large blocks of special characters as character data, but you do not want to have to use entity references all the time.


23.What is XSL?

eXtensible Stylesheet Language(XSL) deals with most displaying the contents of XML documents.XSL consists of three parts:

  • XSLT - a language for transforming XML documents
  • XPath - a language for navigating in XML documents
  • XSL-FO - a language for formatting XML documents

24.How is XSL different from Cascading Style Sheets? Why is a new Stylesheet language needed?

XSL is compatible with CSS and is designed to handle the new capabilities of XML that CSS can't handle. XSL is derived from Document Style Semantics and Specification Language (DSSSL), a complex Stylesheet language with roots in the SGML community. The syntax of XSL is quite different from CSS, which could be used to display simple XML data but isn't general enough to handle all the possibilities generated by XML. XSL adds the capability to handle these possibilities. For instance, CSS cannot add new items or generated text (for instance, to assign a purchase order number) or add a footer (such as an order confirmation). XSL allows for these capabilities.

25.What is XSLT?

eXtensible Stylesheet Language Transformation (XSLT) deals with transformation of one XML document into XHTML documents or to other XML documents. XSLT uses XPath for traversing an XML document and arriving at a particular node.

XSLT

Figure 3: XSLT


26.What is the role of XSL transformer?

An XSL transformer will transform in the following way:

  • The source tree is obtained by parsing in a normal XML style
  • The transformation is now applied to the source with the help of information available in Stylesheet.

27.What is the structure of XSLT?
XSLT Structure

Figure 4: XSLT Structure

28.What is XSL template?

Template specifies transformation rules. A Stylesheet document can be made up of at least one template, which acts as an entry point. Every template uniquely identifies a particular node in the source tree.


29.What is XPath?

XPath is an expression language used for addressing parts of an XML document. XPath is used to navigate through elements and attributes in an XML document.


30.What is XSL-FO?

XSL-FO deals with formatting XML data. This can be used for generating output in a particular format like XML to PDF, XML to DOC, etc.

31.How XSL-FO Works (or) How would you produce PDF output using XSL’s?
XSLT FO

Figure 5: XSL-FO




XML Questions 1

1.What is XML?

* Extensible Markup Language (XML) is the universal language for data on the Web
* XML is a technology which allows us to create our own markup language.
* XML documents are universally accepted as a standard way of representing information in platform and language independent manner.
* XML is universal standard for information interchange.
* XML documents can be created in any language and can be used in any language.


2.What is the difference between XML and HTML?

XML is no way clashes with HTML, since they are for two different purposes.


HTML XML
HTML is for displaying purpose. whereas XML is for data representation.
HTML is used to mark up text so it can be displayed to users. XML is used to mark up data so it can be processed by computers.
HTML describes both structure (e.g.

,

, ) and appearance (e.g.
, , ) XML describes only content, or “meaning”
HTML uses a fixed, unchangeable set of tags In XML, you make up your own tags

3.What are the benefits of XML?

There are many benefits of using XML on the Web :

* Simplicity- Information coded in XML is easy to read and understand, plus it can be processed easily by computers.

* Openness- XML is a W3C standard, endorsed by software industry market leaders.

* Extensibility - There is no fixed set of tags. New tags can be created as they are needed.

* Self-description- In traditional databases, data records require schemas set up by the database administrator. XML documents can be stored without such definitions, because they contain meta data in the form of tags and attributes.

* Contains machine-readable context information- Tags, attributes and element structure provide context information that can be used to interpret the meaning of content, opening up new possibilities for highly efficient search engines, intelligent data mining, agents, etc.

* Separates content from presentation- XML tags describe meaning not presentation. The motto of HTML is: "I know how it looks", whereas the motto of XML is: "I know what it means, and you tell me how it should look." The look and feel of an XML document can be controlled by XSL style sheets, allowing the look of a document to be changed without touching the content of the document. Multiple views or presentations of the same content are easily rendered.

* Supports multilingual documents and Unicode-This is important for the internationalization of applications.

* Facilitates the comparison and aggregation of data - The tree structure of XML documents allows documents to be compared and aggregated efficiently element by element.

* Can embed multiple data types - XML documents can contain any possible data type - from multimedia data (image, sound, video) to active components (Java applets, ActiveX).

* Can embed existing data - Mapping existing data structures like file systems or relational databases to XML is simple. XML supports multiple data formats and can cover all existing data structures and .

* Provides a 'one-server view' for distributed data - XML documents can consist of nested elements that are distributed over multiple remote servers. XML is currently the most sophisticated format for distributed data - the World Wide Web can be seen as one huge XML database.


4.What is a well-formed XML document?

If a document is syntactically correct it can be called as well-formed XML documents. A well-formed document conforms to XML's basic rules of syntax:

* Every open tag must be closed.
* The open tag must exactly match the closing tag: XML is case-sensitive.
* All elements must be embedded within a single root element.
* Child tags must be closed before parent tags.
* A well-formed document has correct XML tag syntax, but the elements might be invalid for the specified document type.


5.What is a valid XML document?

If a document is structurally correct then it can be called as valid XML documents. A valid document conforms to the predefined rules of a specific type of document:

* These rules can be written by the author of the XML document or by someone else.
* The rules determine the type of data that each part of a document can contain.

Note:Valid XML document is implicitly well-formed, but well-formed may not be valid

6.What is the structure of XML document ?
XML Structure

Figure 1: XML Structure

7.What is a Processing Instruction in XML?

A ProcessingIntruction is the information which we would like to give to application. Through a ProcessingInstruction an application would get idea about how to process the document. A ProcessingInstruction can appear anywhere and any no. of times in a document.


8.How does the XML structure is defined?

XML document will have a structure which has to be defined before we can create the documents and work with them. The structural rules can be defined using many available technologies, but the following are popular way of doing so-

  • Document Type Definition (DTD)
  • Schema

9.What is DTD?

A Document Type Definition (DTD) defines the legal building blocks of an XML document. It defines rules for a specific type of document, including:

  • Names of elements, and how and where they can be used
  • The order of elements
  • Proper nesting and containment of elements
  • Element attributes

To apply a DTD to an XML document, you can:

  • Include the DTD's element definitions within the XML document itself.
  • Provide the DTD as a separate file, whose name you reference in the XML document.

10.What is XML Schema?

An XML Schema describes the structure of an XML instance document by defining what each element must or may contain.XML Schema is expressed in the form of a separate XML file.

  • XML Schema provides much more control on element and attribute datatypes.
  • Some datatypes are predefined and new ones can be created.

Xchema

Figure 2: XML Schema


11.What are differences between DTDs and Schema?
Schema DTD
Schema document is an XML document i.e., the structure of an XML document is specified by another XML document. DTDs follow SGML syntax.
Schema supports variety of dataTypes similar to programming language. In DTD everything is treated as text.
In Schema, It is possible to inherit and create relationship among elements. This is not possible in DTD without invalidating existing documents.
In Schema, It is possible to group elements and attributes so that they can be treated as single logical unit. Grouping of elements and attributes is not possible in DTD.
In Schemas, it is possible to specify an upper limit for the number of occurrences of an element It is not possible to specify an upper limit of an element in DTDs

12.What is a Complex Element?

A complex element is an XML element that contains other elements and/or attributes.
There are four kinds of complex elements:

* empty elements
* elements that contain only other elements
* elements that contain only text
* elements that contain both other elements and text


13.What is a Simple Element?

A simple element is an XML element that can contain only text.

* A simple element cannot have attributes
* A simple element cannot contain other elements
* A simple element cannot be empty
* However, the text can be of many different types, and may have various restrictions applied to it


14.What are namespaces? Why are they important?

A simple element is an XML element that can contain only text.

* Namespaces are a simple and straightforward way to distinguish names used in XML documents, no matter where they come from.
* XML namespaces are used for providing uniquely named elements and attributes in an XML instance
* They allow developers to qualify uniquely the element names and relationships and make these names recognizable, to avoid name collisions on elements that have the same name but are defined in different vocabularies.
* They allow tags from multiple namespaces to be mixed, which is essential if data is coming from multiple sources.

tag to mean the title of a book, contained only within the <book> element. A directory of people, however, might define <title> to indicate a person's position, for instance: <title>PresidentExample: a bookstore may define the . Namespaces help define this distinction clearly.

Note: a) Every namespace has a unique name which is a string. To maintain the uniqueness among namespaces a IRL is most preferred approach, since URLs are unique.

b) Except for no-namespace Schemas, every XML Schema uses at least two namespaces:
1.the target namespace.
2. The XMLSchema namespace (http://w3.org/2001/XMLSchema)

15.What are the ways to use namespaces?

There are two ways to use namespaces:

* Declare a default namespace
* Associate a prefix with a namespace, then use the prefix in the XML to refer to the namespace

JDBC Questions 2

16.Which type of JDBC driver is the fastest one?

JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database.


17.Does the JDBC-ODBC Bridge support multiple concurrent open statements per connection?

No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.


18.Which is the right type of driver to use and when?

  • Type I driver is handy for prototyping
  • Type III driver adds security, caching, and connection control
  • Type III and Type IV drivers need no pre-installation
19.What are the standard isolation levels defined by JDBC?

The values are defined in the class java.sql.Connection and are:

  • TRANSACTION_NONE
  • TRANSACTION_READ_COMMITTED
  • TRANSACTION_READ_UNCOMMITTED
  • TRANSACTION_REPEATABLE_READ
  • TRANSACTION_SERIALIZABLE

Any given database may not support all of these levels.


20.What is resultset ?

The ResultSet represents set of rows retrieved due to query execution.

  ResultSet rs = stmt.executeQuery(sqlQuery);

21.What are the types of resultsets?

The values are defined in the class java.sql.Connection and are:

* TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows within it can be advanced only in the forward direction.
* TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either direction but is insensitive to changes committed by other transactions or other statements in the same transaction.
* TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either direction and is affected by changes committed by other transactions or statements within the same transaction.

Note: A TYPE_FORWARD_ONLY resultset is always insensitive.


22.What’s the difference between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE?

TYPE_SCROLL_INSENSITIVE TYPE_SCROLL_SENSITIVE
An insensitive resultset is like the snapshot of the data in the database when query was executed. A sensitive resultset does NOT represent a snapshot of data, rather it contains points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive. After we obtain the resultset if the data is modified then such modifications are visible through resultset.
Performance not effected with insensitive. Since a trip is made for every ‘get’ operation, the performance drastically get affected.

22.What is rowset?

A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. RowSets support component-based development models like JavaBeans, with a standard set of properties and an event notification mechanism.

24.What are the different types of RowSet ?

There are two types of RowSet are there. They are:

* Connected - A connected RowSet object connects to the database once and remains connected until the application terminates.
* Disconnected - A disconnected RowSet object connects to the database, executes a query to retrieve the data from the database and then closes the connection. A program may change the data in a disconnected RowSet while it is disconnected. Modified data can be updated in the database after a disconnected RowSet reestablishes the connection with the database.


25.What is the need of BatchUpdates?

The BatchUpdates feature allows us to group SQL statements together and send to database server in one single trip.

26.What is a DataSource?

A DataSource object is the representation of a data source in the Java programming language. In basic terms,

* A DataSource is a facility for storing data.
* DataSource can be referenced by JNDI.
* Data Source may point to RDBMS, file System , any DBMS etc..


27.What are the advantages of DataSource?

The few advantages of data source are :

* An application does not need to hardcode driver information, as it does with the DriverManager.
* The DataDource implementations can easily change the properties of data sources. For example: There is no need to modify the application code when making changes to the database details.
* The DataSource facility allows developers to implement a DataSource class to take advantage of features like connection pooling and distributed transactions.


28.What is connection pooling? what is the main advantage of using connection pooling?

A connection pool is a mechanism to reuse connections created. Connection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested..

JDBC Questions 1

1.What is the JDBC?

Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form Java. JDBC has set of classes and interfaces which can use from Java application and talk to database without learning RDBMS details and using Database Specific JDBC Drivers.


2.What are the new features added to JDBC 4.0?

The major features added in JDBC 4.0 include :

  • Auto-loading of JDBC driver class
  • Connection management enhancements
  • Support for RowId SQL type
  • DataSet implementation of SQL using Annotations
  • SQL exception handling enhancements
  • SQL XML support
3.Explain Basic Steps in writing a Java program using JDBC?

JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database :

  • Load the RDBMS specific JDBC driver because this driver actually communicates with the database (Incase of JDBC 4.0 this is automatically loaded).
  • Open the connection to database which is then used to send SQL statements and get results back.
  • Create JDBC Statement object. This object contains SQL query.
  • Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query.
  • Process the result set.
  • Close the connection.

4.Exaplain the JDBC Architecture.

The JDBC Architecture consists of two layers:

  • The JDBC API, which provides the application-to-JDBC Manager connection.
  • The JDBC Driver API, which supports the JDBC Manager-to-Driver Connection.

The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the Java application is shown in Figure 1.

JDBC Architecture

Figure 1: JDBC Architecture

5.What are the main components of JDBC ?

The life cycle of a servlet consists of the following phases:

  • DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.

  • Driver: The database communications link, handling all communication with the database. Normally, once the driver is loaded, the developer need not call it explicitly.

  • Connection : Interface with all methods for contacting a database.The connection object represents communication context, i.e., all communication with database is through connection object only.

  • Statement : Encapsulates an SQL statement which is passed to the database to be parsed, compiled, planned and executed.

  • ResultSet: The ResultSet represents set of rows retrieved due to query execution.


6.How the JDBC application works?

A JDBC application can be logically divided into two layers:

1. Driver layer

2. Application layer

  • Driver layer consists of DriverManager class and the available JDBC drivers.
  • The application begins with requesting the DriverManager for the connection.
  • An appropriate driver is choosen and is used for establishing the connection. This connection is given to the application which falls under the application layer.
  • The application uses this connection to create Statement kind of objects, through which SQL commands are sent to backend and obtain the results.
JDBC Application

Figure 2: JDBC Application

7.How do I load a database driver with JDBC 4.0 / Java 6?

Provided the JAR file containing the driver is properly configured, just place the JAR file in the classpath. Java developers NO longer need to explicitly load JDBC drivers using code like Class.forName() to register a JDBC driver.The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.

8.What is JDBC Driver interface?

The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet and Driver.

9.What does the connection object represents?

The connection object represents communication context, i.e., all communication with database is through connection object only.

10.What is Statement ?

Statement acts like a vehicle through which SQL commands can be sent. Through the connection object we create statement kind of objects.
Through the connection object we create statement kind of objects.

Statement stmt = conn.createStatement();

This method returns object which implements statement interface.

11.What is PreparedStatement?

A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.

 PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00);
pstmt.setInt(2, 110592);

Here: conn is an instance of the Connection class and "?" represents parameters.These parameters must be specified before execution.




12.What is the difference between a Statement and a PreparedStatement?

Statement PreparedStatement
A standard Statement is used to create a Java representation of a literal SQL statement and execute it on the database. A PreparedStatement is a precompiled statement. This means that when the PreparedStatement is executed, the RDBMS can just run the PreparedStatement SQL statement without having to compile it first.
Statement has to verify its metadata against the database every time. While a prepared statement has to verify its metadata against the database only once.
If you want to execute the SQL statement once go for STATEMENT If you want to execute a single SQL statement multiple number of times, then go for PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing different values to the queries


13.What are callable statements ?

Callable statements are used from JDBC application to invoke stored procedures and functions.


14.How to call a stored procedure from JDBC ?

PL/SQL stored procedures are called from within JDBC programs by means of the prepareCall() method of the Connection object created. A call to this method takes variable bind parameters as input parameters as well as output variables and creates an object instance of the CallableStatement class.

The following line of code illustrates this:

   CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");

Here conn is an instance of the Connection class.


15.What are types of JDBC drivers?

There are four types of drivers defined by JDBC as follows:

  • Type 1: JDBC/ODBC—These require an ODBC (Open Database Connectivity) driver for the database to be installed. This type of driver works by translating the submitted queries into equivalent ODBC queries and forwards them via native API calls directly to the ODBC driver. It provides no host redirection capability.

  • Type2: Native API (partly-Java driver)—This type of driver uses a vendor-specific driver or database API to interact with the database. An example of such an API is Oracle OCI (Oracle Call Interface). It also provides no host redirection.

  • Type 3: Open Protocol-Net—This is not vendor specific and works by forwarding database requests to a remote database source using a net server component. How the net server component accesses the database is transparent to the client. The client driver communicates with the net server using a database-independent protocol and the net server translates this protocol into database calls. This type of driver can access any database.

  • Type 4: Proprietary Protocol-Net(pure Java driver)—This has a same configuration as a type 3 driver but uses a wire protocol specific to a particular vendor and hence can access only that vendor's database. Again this is all transparent to the client.

Note: Type 4 JDBC driver is most preferred kind of approach in JDBC.


Servlet Questions 3

30.What is session?

A session refers to all the requests that a single client might make to a server in the course of viewing any pages associated with a given application. Sessions are specific to both the individual user and the application. As a result, every user of an application has a separate session and has access to a separate set of session variables.

Session





31.What is Session Tracking?

Session tracking is a mechanism that servlets use to maintain state about a series of requests from the same user (that is, requests originating from the same browser) across some period of time.

32.What is the need of Session Tracking in web application?

HTTP is a stateless protocol i.e., every request is treated as new request. For web applications to be more realistic they have to retain information across multiple requests. Such information which is part of the application is reffered as "state". To keep track of this state we need session tracking.

Typical example: Putting things one at a time into a shopping cart, then checking out--each page request must somehow be associated with previous requests.

33.What are the types of Session Tracking ?

Sessions need to work with all web browsers and take into account the users security preferences. Therefore there are a variety of ways to send and receive the identifier:

* URL rewriting : URL rewriting is a method of session tracking in which some extra data (session ID) is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session. This method is used with browsers that do not support cookies or where the user has disabled the cookies.

* Hidden Form Fields : Similar to URL rewriting. The server embeds new hidden fields in every dynamically generated form page for the client. When the client submits the form to the server the hidden fields identify the client.

* Cookies : Cookie is a small amount of information sent by a servlet to a Web browser. Saved by the browser, and later sent back to the server in subsequent requests. A cookie has a name, a single value, and optional attributes. A cookie's value can uniquely identify a client.

* Secure Socket Layer (SSL) Sessions : Web browsers that support Secure Socket Layer communication can use SSL's support via HTTPS for generating a unique session key as part of the encrypted conversation.

Learn more about Session Tracking


34.How do I use cookies to store session state on the client?

In a servlet, the HttpServletResponse and HttpServletRequest objects passed to method HttpServlet.service() can be used to create cookies on the client and use cookie information transmitted during client requests. JSPs can also use cookies, in scriptlet code or, preferably, from within custom tag code.

* To set a cookie on the client, use the addCookie() method in class HttpServletResponse. Multiple cookies may be set for the same request, and a single cookie name may have multiple values.
* To get all of the cookies associated with a single HTTP request, use the getCookies() method of class HttpServletRequest


35.What are some advantages of storing session state in cookies?

* Cookies are usually persistent, so for low-security sites, user data that needs to be stored long-term (such as a user ID, historical information, etc.) can be maintained easily with no server interaction.
* For small- and medium-sized session data, the entire session data (instead of just the session ID) can be kept in the cookie.

36.What are some disadvantages of storing session state in cookies?
  • Cookies are controlled by programming a low-level API, which is more difficult to implement than some other approaches.
  • All data for a session are kept on the client. Corruption, expiration or purging of cookie files can all result in incomplete, inconsistent, or missing information.
  • Cookies may not be available for many reasons: the user may have disabled them, the browser version may not support them, the browser may be behind a firewall that filters cookies, and so on. Servlets and JSP pages that rely exclusively on cookies for client-side session state will not operate properly for all clients. Using cookies, and then switching to an alternate client-side session state strategy in cases where cookies aren't available, complicates development and maintenance.
  • Browser instances share cookies, so users cannot have multiple simultaneous sessions.
  • Cookie-based solutions work only for HTTP clients. This is because cookies are a feature of the HTTP protocol. Notice that the while package javax.servlet.http supports session management (via class HttpSession), package javax.servlet has no such support.

37.What is URL rewriting?

URL rewriting is a method of session tracking in which some extra data is appended at the end of each URL. This extra data identifies the session. The server can associate this session identifier with the data it has stored about that session.

Every URL on the page must be encoded using method HttpServletResponse.encodeURL(). Each time a URL is output, the servlet passes the URL to encodeURL(), which encodes session ID in the URL if the browser isn't accepting cookies, or if the session tracking is turned off.
E.g., http://abc/path/index.jsp;jsessionid=123465hfhs

    Advantages
  • URL rewriting works just about everywhere, especially when cookies are turned off.
  • Multiple simultaneous sessions are possible for a single user. Session information is local to each browser instance, since it's stored in URLs in each page being displayed. This scheme isn't foolproof, though, since users can start a new browser instance using a URL for an active session, and confuse the server by interacting with the same session through two instances.
  • Entirely static pages cannot be used with URL rewriting, since every link must be dynamically written with the session state. It is possible to combine static and dynamic content, using (for example) templating or server-side includes. This limitation is also a barrier to integrating legacy web pages with newer, servlet-based pages.

    DisAdvantages
  • Every URL on a page which needs the session information must be rewritten each time a page is served. Not only is this expensive computationally, but it can greatly increase communication overhead.
  • URL rewriting limits the client's interaction with the server to HTTP GETs, which can result in awkward restrictions on the page.
  • URL rewriting does not work well with JSP technology.
  • If a client workstation crashes, all of the URLs (and therefore all of the data for that session) are lost.
38.How can an existing session be invalidated?

An existing session can be invalidated in the following two ways:

  • Setting timeout in the deployment descriptor: This can be done by specifying timeout between the tags as follows:

  • <session-timeout>10

    This will set the time for session timeout to be ten minutes.


  • Setting timeout programmatically: This will set the timeout for a specific session. The syntax for setting the timeout programmatically is as follows:
  • public void setMaxInactiveInterval(int interval)
    The setMaxInactiveInterval() method sets the maximum time in seconds before a session becomes invalid.
    Note :Setting the inactive period as negative(-1), makes the container stop tracking session, i.e, session never expires.

39.How can the session in Servlet can be destroyed?

An existing session can be destroyed in the following two ways:

  • Programatically : Using session.invalidate() method, which makes the container abonden the session on which the method is called.
  • When the server itself is shutdown.

40.A client sends requests to two different web components. Both of the components access the session. Will they end up using the same session object or different session ?

Creates only one session i.e., they end up with using same session .

Sessions is specific to the client but not the web components. And there is a 1-1 mapping between client and a session.


41.What is servlet lazy loading?
  • A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading.
  • The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up.
  • The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.

42.What is Servlet Chaining?

Servlet Chaining is a method where the output of one servlet is piped into a second servlet. The output of the second servlet could be piped into a third servlet, and so on. The last servlet in the chain returns the output to the Web browser.


43.How are filters?

Filters are Java components that are used to intercept an incoming request to a Web resource and a response sent back from the resource. It is used to abstract any useful information contained in the request or response. Some of the important functions performed by filters are as follows:

  • Security checks
  • Modifying the request or response
  • Data compression
  • Logging and auditing
  • Response compression

Filters are configured in the deployment descriptor of a Web application. Hence, a user is not required to recompile anything to change the input or output of the Web application.


44.What are the functions of an intercepting filter?

The functions of an intercepting filter are as follows:

  • It intercepts the request from a client before it reaches the servlet and modifies the request if required.
  • It intercepts the response from the servlet back to the client and modifies the request if required.
  • There can be many filters forming a chain, in which case the output of one filter becomes an input to the next filter. Hence, various modifications can be performed on a single request and response.
Intercepting Filter.gif


45.What are the functions of the Servlet container?

The functions of the Servlet container are as follows:

  • Lifecycle management : It manages the life and death of a servlet, such as class loading, instantiation, initialization, service, and making servlet instances eligible for garbage collection.
  • Communication support : It handles the communication between the servlet and the Web server.
  • Multithreading support : It automatically creates a new thread for every servlet request received. When the Servlet service() method completes, the thread dies.
  • Declarative security : It manages the security inside the XML deployment descriptor file.
  • JSP support : The container is responsible for converting JSPs to servlets and for maintaining them.




Servlet Questions 2

16.When to use doGet() and when doPost()?

Always prefer to use GET (As because GET is faster than POST), except mentioned in the following reason:

* If data is sensitive
* Date is greater than 1024 characters
* If your application don't need bookmarks.


17.How do I support both GET and POST from the same Servlet?

The easy way is, just support POST, then have your doGet method call your doPost method:

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
doPost(request, response);
}


18.Should I override the service() method?

We never override the service method, since the HTTP Servlets have already taken care of it . The default service function invokes the doXXX() method corresponding to the method of the HTTP request.For example, if the HTTP request method is GET, doGet() method is called by default. A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method check the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.

19.How the typical servlet code look like ?
Servlet Code

20.What is a servlet context object?

A servlet context object contains the information about the Web application of which the servlet is a part. It also provides access to the resources common to all the servlets in the application. Each Web application in a container has a single servlet context associated with it.


21.What are the differences between the ServletConfig interface and the ServletContext interface?

ServletConfig ServletContext
The ServletConfig interface is implemented by the servlet container in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method. A ServletContext defines a set of methods that a servlet uses to communicate with its servlet container.
There is one ServletConfig parameter per servlet. There is one ServletContext for the entire webapp and all the servlets in a webapp share it.
The param-value pairs for ServletConfig object are specified in the within the tags in the web.xml file The param-value pairs for ServletContext object are specified in the tags in the web.xml file.



22.What's the difference between forward() and sendRedirect() methods?

forward() sendRedirect()
A forward is performed internally by the servlet. A redirect is a two step process, where the web application instructs the browser to fetch a second URL, which differs from the original.
The browser is completely unaware that it has taken place, so its original URL remains intact. The browser, in this case, is doing the work and knows that it's making a new request.
Any browser reload of the resulting page will simple repeat the original request, with the original URL A browser reloads of the second URL ,will not repeat the original request, but will rather fetch the second URL.
Both resources must be part of the same context (Some containers make provisions for cross-context communication but this tends not to be very portable) This method can be used to redirect users to resources that are not part of the current context, or even in the same domain.
Since both resources are part of same context, the original request context is retained Because this involves a new request, the previous request scope objects, with all of its parameters and attributes are no longer available after a redirect.
(Variables will need to be passed by via the session object).
Forward is marginally faster than redirect. redirect is marginally slower than a forward, since it requires two browser requests, not one.



23.What is the difference between the include() and forward() methods?
include() forward()
The RequestDispatcher include() method inserts the the contents of the specified resource directly in the flow of the servlet response, as if it were part of the calling servlet. The RequestDispatcher forward() method is used to show a different resource in place of the servlet that was originally called.
If you include a servlet or JSP document, the included resource must not attempt to change the response status code or HTTP headers, any such request will be ignored. The forwarded resource may be another servlet, JSP or static HTML document, but the response is issued under the same URL that was originally requested. In other words, it is not the same as a redirection.
The include() method is often used to include common "boilerplate" text or template markup that may be included by many servlets. The forward() method is often used where a servlet is taking a controller role; processing some input and deciding the outcome by returning a particular response page.


24.What's the use of the servlet wrapper classes??

The HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed to make it easy for developers to create custom implementations of the servlet request and response types. The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.
25.What is the directory structure of a WAR file?
WAR directory structure
26.What is a deployment descriptor?

A deployment descriptor is an XML document with an .xml extension. It defines a component's deployment settings. It declares transaction attributes and security authorization for an enterprise bean. The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
The JavaEE server reads the deployment descriptor at run time and acts upon the component accordingly.


27.What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
ServletRequest.getRequestDispatcher(String path) ServletContext.getRequestDispatcher(String path)

The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a “/” it is interpreted as relative to the current context root.

The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept relative paths. All path must start with a “/” and are interpreted as relative to current context root.

28.What is preinitialization of a servlet?

A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.


29.What is the element?

The element of a deployment descriptor is used to load a servlet file when the server starts instead of waiting for the first request. It is also used to specify the order in which the files are to be loaded. The element is written in the deployment descriptor as follows:


ServletName
ClassName
1


Note: The container loads the servlets in the order specified in the element.

Servlet Questions 1

1.What is the Servlet?

A servlet is a Java programming language class that is used to extend the capabilities of servers that host applications accessed by means of a request- response programming model.

2.What are the new features added to Servlet 2.5?

Following are the changes introduced in Servlet 2.5:

* A new dependency on J2SE 5.0
* Support for annotations
* Loading the class
* Several web.xml conveniences
* A handful of removed restrictions
* Some edge case clarifications
3.What are the uses of Servlet?

Typical uses for HTTP Servlets include:

  • Processing and/or storing data submitted by an HTML form.
  • Providing dynamic content, e.g. returning the results of a database query to the client.
  • A Servlet can handle multiple request concurrently and be used to develop high performance system
  • Managing state information on top of the stateless HTTP, e.g. for an online shopping cart system which manages shopping carts for many concurrent customers and maps every request to the right customer.

4.What are the advantages of Servlet over CGI?

Servlets have several advantages over CGI:

  • A Servlet does not run in a separate process. This removes the overhead of creating a new process for each request.
  • A Servlet stays in memory between requests. A CGI program (and probably also an extensive runtime system or interpreter) needs to be loaded and started for each CGI request.
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Several web.xml conveniences
  • A handful of removed restrictions
  • Some edge case clarifications

5.What are the phases of the servlet life cycle?

The life cycle of a servlet consists of the following phases:

  • Servlet class loading : For each servlet defined in the deployment descriptor of the Web application, the servlet container locates and loads a class of the type of the servlet. This can happen when the servlet engine itself is started, or later when a client request is actually delegated to the servlet.

  • Servlet instantiation : After loading, it instantiates one or more object instances of the servlet class to service the client requests.

  • Initialization (call the init method) : After instantiation, the container initializes a servlet before it is ready to handle client requests. The container initializes the servlet by invoking its init() method, passing an object implementing the ServletConfig interface. In the init() method, the servlet can read configuration parameters from the deployment descriptor or perform any other one-time activities, so the init() method is invoked once and only once by the servlet container.

  • Request handling (call the service method) : After the servlet is initialized, the container may keep it ready for handling client requests. When client requests arrive, they are delegated to the servlet through the service() method, passing the request and response objects as parameters. In the case of HTTP requests, the request and response objects are implementations of HttpServletRequest and HttpServletResponse respectively. In the HttpServlet class, the service() method invokes a different handler method for each type of HTTP request, doGet() method for GET requests, doPost() method for POST requests, and so on.

  • Removal from service (call the destroy method) : A servlet container may decide to remove a servlet from service for various reasons, such as to conserve memory resources. To do this, the servlet container calls the destroy() method on the servlet. Once the destroy() method has been called, the servlet may not service any more client requests. Now the servlet instance is eligible for garbage collection
  • The life cycle of a servlet is controlled by the container in which the servlet has been deployed.

    Servlet Lifecycle


6.Why do we need a constructor in a servlet if we use the init method?

Even though there is an init method in a servlet which gets called to initialize it, a constructor is still required to instantiate the servlet. Even though you as the developer would never need to explicitly call the servlet's constructor, it is still being used by the container (the container still uses the constructor to create an instance of the servlet). Just like a normal POJO (plain old java object) that might have an init method, it is no use calling the init method if you haven't constructed an object to call it on yet.


7.How the servlet is loaded?

A servlet can be loaded when:

  • First request is made.
  • Server starts up (auto-load).
  • There is only a single instance which answers all requests concurrently. This saves memory and allows a Servlet to easily manage persistent data.
  • Administrator manually loads.

8.How a Servlet is unloaded?

A servlet is unloaded when:

  • Server shuts down.
  • Administrator manually unloads.

9.What is Servlet interface?

The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or , more commonly by extending a class that implements it.

Servlet

Note: Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.

10.What is the GenericServlet class?

GenericServlet is an abstract class that implements the Servlet interface and the ServletConfig interface. In addition to the methods declared in these two interfaces, this class also provides simple versions of the lifecycle methods init and destroy, and implements the log method declared in the ServletContext interface.
Note: This class is known as generic servlet, since it is not specific to any protocol.

11.What's the difference between GenericServlet and HttpServlet?

GenericServlet HttpServlet
The GenericServlet is an abstract class that is extended by HttpServlet to provide HTTP protocol-specific methods. An abstract class that simplifies writing HTTP servlets. It extends the GenericServlet base class and provides an framework for handling the HTTP protocol.
The GenericServlet does not include protocol-specific methods for handling request parameters, cookies, sessions and setting response headers. The HttpServlet subclass passes generic service method requests to the relevant doGet() or doPost() method.
GenericServlet is not specific to any protocol. HttpServlet only supports HTTP and HTTPS protocol.

12.Why is HttpServlet declared abstract?

The HttpServlet class is declared abstract because the default implementations of the main service methods do nothing and must be overridden. This is a convenience implementation of the Servlet interface, which means that developers do not need to implement all service methods. If your servlet is required to handle doGet() requests for example, there is no need to write a doPost() method too.

13.Can servlet have a constructor ?

One can definitely have constructor in servlet.Even you can use the constrctor in servlet for initialization purpose,but this type of approch is not so common. You can perform common operations with the constructor as you normally do.The only thing is that you cannot call that constructor explicitly by the new keyword as we normally do.In the case of servlet, servlet container is responsible for instantiating the servlet, so the constructor is also called by servlet container only.

14.What are the types of protocols supported by HttpServlet ?

It extends the GenericServlet base class and provides a framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.

15.What is the difference between doGet() and doPost()?
#
doGet() doPost()
1
In doGet() the parameters are appended to the URL and sent along with header information. In doPost(), on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar.
2
The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
3
doGet() is a request for information; it does not (or should not) change anything on the server. (doGet() should be idempotent) doPost() provides information (such as placing an order for merchandise) that the server is expected to remember
4
Parameters are not encrypted Parameters are encrypted
5
doGet() is faster if we set the response content length since the same connection is used. Thus increasing the performance doPost() is generally used to update or post some information to the server.doPost is slower compared to doGet since doPost does not write the content length
6
doGet() should be idempotent. i.e. doget should be able to be repeated safely many times This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable.
7
doGet() should be safe without any side effects for which user is held responsible This method does not need to be either safe
8
It allows bookmarks. It disallows bookmarks.

Hibernate Interview questions 3

31.What is the advantage of Hibernate over jdbc? Hibernate Vs. JDBC :-
JDBC Hibernate
With JDBC, developer has to write code to map an object model's data representation to a relational data model and its corresponding database schema. Hibernate is flexible and powerful ORM solution to map Java classes to database tables. Hibernate itself takes care of this mapping using XML files so developer does not need to write code for this.
With JDBC, the automatic mapping of Java objects with database tables and vice versa conversion is to be taken care of by the developer manually with lines of code. Hibernate provides transparent persistence and developer does not need to write code explicitly to map database tables tuples to application objects during interaction with RDBMS.
JDBC supports only native Structured Query Language (SQL). Developer has to find out the efficient way to access database, i.e. to select effective query from a number of queries to perform same task. Hibernate provides a powerful query language Hibernate Query Language (independent from type of database) that is expressed in a familiar SQL like syntax and includes full support for polymorphic queries. Hibernate also supports native SQL statements. It also selects an effective way to perform a database manipulation task for an application.
Application using JDBC to handle persistent data (database tables) having database specific code in large amount. The code written to map table data to application objects and vice versa is actually to map table fields to object properties. As table changed or database changed then it’s essential to change object structure as well as to change code written to map table-to-object/object-to-table. Hibernate provides this mapping itself. The actual mapping between tables and application objects is done in XML files. If there is change in Database or in any table then the only need to change XML file properties.
With JDBC, it is developer’s responsibility to handle JDBC result set and convert it to Java objects through code to use this persistent data in application. So with JDBC, mapping between Java objects and database tables is done manually. Hibernate reduces lines of code by maintaining object-table mapping itself and returns result to application in form of Java objects. It relieves programmer from manual handling of persistent data, hence reducing the development time and maintenance cost.
With JDBC, caching is maintained by hand-coding. Hibernate, with Transparent Persistence, cache is set to application work space. Relational tuples are moved to this cache as a result of query. It improves performance if client application reads same data many times for same write. Automatic Transparent Persistence allows the developer to concentrate more on business logic rather than this application code.
In JDBC there is no check that always every user has updated data. This check has to be added by the developer. Hibernate enables developer to define version type field to application, due to this defined field Hibernate updates version field of database table every time relational tuple is updated in form of Java class object to that table. So if two users retrieve same tuple and then modify it and one user save this modified tuple to database, version is automatically updated for this tuple by Hibernate. When other user tries to save updated tuple to database then it does not allow saving it because this user does not have updated data.

32.What are the Collection types in Hibernate ?

* Bag
* Set
* List
* Array
* Map


33.What are the ways to express joins in HQL?

HQL provides four ways of expressing (inner and outer) joins:-

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


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

cascade - enable operations to cascade to child entities.
cascade="all|none|save-update|delete|all-delete-orphan"

inverse - mark this collection as the "inverse" end of a bidirectional association.
inverse="true|false"
Essentially "inverse" indicates which end of a relationship should be ignored, so when persisting a parent who has a collection of children, should you ask the parent for its list of children, or ask the children who the parents are?

35.What is Hibernate proxy?

The proxy attribute enables lazy initialization of persistent instances of the class. Hibernate will initially return CGLIB proxies which implement the named interface. The actual persistent object will be loaded when a method of the proxy is invoked.

36.How can Hibernate be configured to access an instance variable directly and not through a setter method ?

By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

37.How can a whole class be mapped as immutable?

Mark the class as mutable="false" (Default is true),. This specifies that instances of the class are (not) mutable. Immutable classes, may not be updated or deleted by the application.

38.What is the use of dynamic-insert and dynamic-update attributes in a class mapping?

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

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


39.What do you mean by fetching strategy ?

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

40.What is automatic dirty checking?

Automatic dirty checking is a feature that saves us the effort of explicitly asking Hibernate to update the database when we modify the state of an object inside a transaction.

41.What is transactional write-behind?

Hibernate uses a sophisticated algorithm to determine an efficient ordering that avoids database foreign key constraint violations but is still sufficiently predictable to the user. This feature is called transactional write-behind.
People who read this also read:
JSP Interview Questions
Tibco Questions
webMethods Certification
Hibernate Interview Questions
XML Questions

42.What are Callback interfaces?

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

43.What are the types of Hibernate instance states ?

Three types of instance states:

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

44.What are the differences between EJB 3.0 & Hibernate

Hibernate Vs EJB 3.0 :-

Hibernate EJB 3.0
Session–Cache or collection of loaded objects relating to a single unit of work Persistence Context-Set of entities that can be managed by a given EntityManager is defined by a persistence unit
XDoclet Annotations used to support Attribute Oriented Programming Java 5.0 Annotations used to support Attribute Oriented Programming
Defines HQL for expressing queries to the database Defines EJB QL for expressing queries
Supports Entity Relationships through mapping files and annotations in JavaDoc Support Entity Relationships through Java 5.0 annotations
Provides a Persistence Manager API exposed via the Session, Query, Criteria, and Transaction API Provides and Entity Manager Interface for managing CRUD operations for an Entity
Provides callback support through lifecycle, interceptor, and validatable interfaces Provides callback support through Entity Listener and Callback methods
Entity Relationships are unidirectional. Bidirectional relationships are implemented by two unidirectional relationships Entity Relationships are bidirectional or unidirectional


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

There are three types of inheritance models in Hibernate:

  • Table per class hierarchy
  • Table per subclass
  • Table per concrete class

Topics