1.what Is ORM ?: Improved Productivity
1.what Is ORM ?: Improved Productivity
ORM stands for object/relational mapping. ORM is the automated persistence of objects in a Java
application to the tables in a relational database.
4.What is Hibernate?
Hibernate is a pure Java object-relational mapping (ORM) and persistence framework that allows you
to map plain old Java objects to relational database tables using (XML) configuration files.Its purpose is
to relieve the developer from a significant amount of relational data persistence-related programming
tasks.
• Improved productivity
o High-level object-oriented API
o Less Java code to write
o No SQL to write
• Improved performance
o Sophisticated caching
o Lazy loading
o Eager loading
• Improved maintainability
o A lot less code to write
• Improved portability
o ORM framework generates database-specific SQL for you
• Programmatic configuration
• XML configuration (hibernate.cfg.xml)
• Load the Hibernate configuration file and create configuration object. It will automatically
load all hbm mapping files
• Create session factory from configuration object
• Get one session from this session factory
• Create HQL Query
• Execute query to get list containing Java objects
• First we need to write Java domain objects (beans with setter and getter).
• Write hbm.xml, where we map java class to table and database columns to Java class
variables.
Example :
<hibernate-mapping>
<class name="com.test.User" table="user">
<property column="USER_NAME" length="255"
name="userName" not-null="true" type="java.lang.String"/>
<property column="USER_PASSWORD" length="255"
name="userPassword" not-null="true" type="java.lang.String"/>
</class>
</hibernate-mapping>
load() get()
Only use the load() method if you are sure that the If you are not sure that the object exists,
object exists. then use one of the get() methods.
load() method will throw an exception if the get() method will return null if the unique
unique id is not found in the database. id is not found in the database.
23.Define HibernateTemplate?
org.springframework.orm.hibernate.HibernateTemplate is a helper class which provides different
methods for querying/retrieving data from the database. It also converts checked HibernateExceptions
into unchecked DataAccessExceptions.
26.If you want to see the Hibernate generated SQL statements on console, what should we do?
In Hibernate configuration file set as follows:
<property name="show_sql">true</property>
Example:
JDBC Hibernate
With JDBC, the automatic mapping of Java Hibernate provides transparent persistence and
objects with database tables and vice versa developer does not need to write code explicitly
conversion is to be taken care of by the to map database tables tuples to application
developer manually with lines of code. objects during interaction with RDBMS.
In JDBC there is no check that always every user 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
has updated data. This check has to be added by
one user save this modified tuple to database,
the developer.
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.
• Bag
• Set
• List
• Array
• Map
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.
XDoclet Annotations used to support Attribute Java 5.0 Annotations used to support Attribute
Oriented Programming Oriented Programming
Supports Entity Relationships through mapping Support Entity Relationships through Java 5.0
files and annotations in JavaDoc annotations
Provides a Persistence Manager API exposed via Provides and Entity Manager Interface for
the Session, Query, Criteria, and Transaction API managing CRUD operations for an Entity
Provides callback support through lifecycle, Provides callback support through Entity
interceptor, and validatable interfaces Listener and Callback methods
Q. What are the different types of dependency injection. Explain with examples.
A: There are two types of dependency injection: setter injection and constructor
injection.
Setter Injection: Normally in all the java beans, we will use setter and getter method
to set and get the value of property as follows:
We will create an instance of the bean 'namebean' (say bean1) and set property as
bean1.setName("tom"); Here in setter injection, we will set the property 'name' in spring
configuration file as showm below:
<bean id="bean1" class="namebean">
<property name="name" >
<value>tom</value>
</property>
</bean>
The subelement <value> sets the 'name' property by calling the set method as
setName("tom"); This process is called setter injection.
To set properties that reference other beans <ref>, subelement of <property> is used as
shown below,
<bean id="bean1" class="bean1impl">
<property name="game">
<ref bean="bean2"/>
</property>
</bean>
<bean id="bean2" class="bean2impl" />
We will set the property 'name' while creating an instance of the bean 'namebean' as
namebean bean1 = new namebean("tom");
Here we use the <constructor-arg> element to set the the property by constructor injection as
Q. What is spring? What are the various parts of spring framework? What are the
different persistence frameworks which could be used with spring?
A. Spring is an open source framework created to address the complexity of
enterprise application development. One of the chief advantages of the Spring
framework is its layered architecture, which allows you to be selective about which of
its components you use while also providing a cohesive framework for J2EE
application development. The Spring modules are built on top of the core container,
which defines how beans are created, configured, and managed, as shown in the
following figure. Each of the modules (or components) that comprise the Spring
framework can stand on its own or be implemented jointly with one or more of the
others. The functionality of each component is as follows:
The core container: The core container provides the essential functionality of the
Spring framework. A primary component of the core container is the BeanFactory, an
implementation of the Factory pattern. The BeanFactory applies the Inversion of
Control (IOC) pattern to separate an application’s configuration and dependency
specification from the actual application code.
Spring context: The Spring context is a configuration file that provides context
information to the Spring framework. The Spring context includes enterprise services
such as JNDI, EJB, e-mail, internalization, validation, and scheduling functionality.
Spring DAO: The Spring JDBC DAO abstraction layer offers a meaningful exception
hierarchy for managing the exception handling and error messages thrown by
different database vendors. The exception hierarchy simplifies error handling and
greatly reduces the amount of exception code you need to write, such as opening and
closing connections. Spring DAO’s JDBC-oriented exceptions comply to its generic DAO
exception hierarchy.
Spring ORM: The Spring framework plugs into several ORM frameworks to provide its
Object Relational tool, including JDO, Hibernate, and iBatis SQL Maps. All of these
comply to Spring’s generic transaction and DAO exception hierarchies.
Spring Web module: The Web context module builds on top of the application context
module, providing contexts for Web-based applications. As a result, the Spring
framework supports integration with Jakarta Struts. The Web module also eases the
tasks of handling multi-part requests and binding request parameters to domain
objects.
Q. What is AOP? How does it relate with IOC? What are different tools to utilize AOP?
A: Aspect-oriented programming, or AOP, is a programming technique that allows
programmers to modularize crosscutting concerns, or behavior that cuts across the
typical divisions of responsibility, such as logging and transaction management. The
core construct of AOP is the aspect, which encapsulates behaviors affecting multiple
classes into reusable modules. AOP and IOC are complementary technologies in that
both apply a modular approach to complex problems in enterprise application
development. In a typical object-oriented development approach you might
implement logging functionality by putting logger statements in all your methods and
Java classes. In an AOP approach you would instead modularize the logging services
and apply them declaratively to the components that required logging. The
advantage, of course, is that the Java class doesn't need to know about the existence
of the logging service or concern itself with any related code. As a result, application
code written using Spring AOP is loosely coupled. The best tool to utilize AOP to its
capability is AspectJ. However AspectJ works at he byte code level and you need to
use AspectJ compiler to get the aop features built into your compiled code.
Nevertheless AOP functionality is fully integrated into the Spring context for
transaction management, logging, and various other features. In general any AOP
framework control aspects in three possible ways:
Joinpoints: Points in a program's execution. For example, joinpoints could define calls to
specific methods in a class
Pointcuts: Program constructs to designate joinpoints and collect specific context at those
points
Advices: Code that runs upon meeting certain conditions. For example, an advice could log a
message before executing a joinpoint
1. Spring has layed architecture. Use what you need and leave you don't need now.
2. Spring Enables POJO Programming. There is no behind the scene magic here. POJO
programming enables continous integration and testability.
3. Dependency Injection and Inversion of Control Simplifies JDBC (Read the first
question.)
4. Open source and no vendor lock-in.
Q. Can you name a tool which could provide the initial ant files and directory
structure for a new spring project.
A: Appfuse or equinox.
<property name="mappingResources">
<list>
<value>org/appfuse/model/User.hbm.xml</value>
</list>
</property>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/xyz.xml</param-value>
</context-param>
</listener-class>
</listener>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>org.hsqldb.jdbcDriver</value>
</property>
<property name="url">
<value>jdbc:hsqldb:db/appfuse</value>
</property>
<property name="username"><value>sa</value></property>
<property name="password"><value></value></property>
</bean>
Q. What is hibernate session and session factory? How do you configure sessionfactory
in spring configuration file?
A. Hibernate Session is the main runtime interface between a Java application and
Hibernate. SessionFactory allows applications to create hibernate session by reading
hibernate configurations file hibernate.cfg.xml.
A Hibernate Session object represents a single unit-of-work for a given data store and
is opened by a SessionFactory instance. You must close Sessions when all work for a
transaction is completed. The following illustrates a typical Hibernate session:
Session session = null;
UserInfo user = null;
Transaction tx = null;
try {
session = factory.openSession();
tx = session.beginTransaction();
user = (UserInfo)session.load(UserInfo.class, id);
tx.commit();
} catch(Exception e) {
if (tx != null) {
try {
tx.rollback();
} catch (HibernateException e1) {
throw new DAOException(e1.toString()); }
} throw new DAOException(e.toString());
} finally {
if (session != null) {
try {
session.close();
} catch (HibernateException e) { }
}
}
<bean id="transactionManager"
class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="transactionManager"
class="org.springframework.transaction.jta.JtaTransactionManager.">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
Join fetching - Hibernate retrieves the associated instance or collection in the same SELECT,
using an OUTER JOIN.
Select fetching - a second SELECT is used to retrieve the associated entity or collection.
Unless you explicitly disable lazy fetching by specifying lazy="false", this second select will
only be executed when you actually access the association.
Subselect fetching - a second SELECT is used to retrieve the associated collections for all
entities retrieved in a previous query or fetch. Unless you explicitly disable lazy fetching by
specifying lazy="false", this second select will only be executed when you actually access the
association.Batch fetching - an optimization strategy for select fetching - Hibernate retrieves
a batch of entity instances or collections in a single SELECT, by specifying a list of primary
keys or foreign keys.
For more details read short primer on fetching strategy at
http://www.hibernate.org/315.html
• Read-only: This strategy is useful for data that is read frequently but never updated.
This is by far the simplest and best-performing cache strategy.
• Read/write: Read/write caches may be appropriate if your data needs to be updated.
They carry more overhead than read-only caches. In non-JTA environments, each
transaction should be completed when Session.close() or Session.disconnect() is
called.
• Nonstrict read/write: This strategy does not guarantee that two transactions won't
simultaneously modify the same data. Therefore, it may be most appropriate for data
that is read often but only occasionally modified.
• Transactional: This is a fully transactional cache that may be used only in a JTA
environment.
Q. What are the types of inheritence models and describe how they work like vertical
inheritence and horizontal?
A. There are three types of inheritance mapping in hibernate :
Example: Let us take the simple example of 3 java classes. Class Manager and Worker are
inherited from Employee Abstract class.
1. Table per concrete class with unions : In this case there will be 2 tables. Tables: Manager,
Worker [all common attributes will be duplicated]
2. Table per class hierarchy: Single Table can be mapped to a class hierarchy. There will be
only one table in database called 'Employee' that will represent all the attributes required for
all 3 classes. But it needs some discriminating column to differentiate between Manager and
worker;
3. Table per subclass: In this case there will be 3 tables represent Employee, Manager and
Worker