0% found this document useful (0 votes)
2 views43 pages

Application Development Using Advance Java

The document provides an overview of the Spring Framework, detailing its advantages, modules, and dependency injection methods including Constructor Injection (CI) and Setter Injection (SI). It explains the structure of the framework, the purpose of various modules, and how dependency injection can be implemented using XML configuration. Additionally, it compares CI and SI, highlighting their differences and use cases.

Uploaded by

harshadshukla23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views43 pages

Application Development Using Advance Java

The document provides an overview of the Spring Framework, detailing its advantages, modules, and dependency injection methods including Constructor Injection (CI) and Setter Injection (SI). It explains the structure of the framework, the purpose of various modules, and how dependency injection can be implemented using XML configuration. Additionally, it compares CI and SI, highlighting their differences and use cases.

Uploaded by

harshadshukla23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

M.Sc.

(IT & CA) (Semester – 1) ADVANCE JAVA

Question: 1 What Is Spring? Explain Advantages Of Spring Framework.

Answer:

 Spring framework is an open source Java platform that provides comprehensive infrastructure support for
developing robust Java applications very easily and very rapidly.
 Spring framework was initially written by Rod Johnson and was first released under the Apache 2.0 license in
June 2003.

Advantages of Spring Framework:

1. Predefined Templates:
- Spring framework provides templates for JDBC, Hibernate, JPA etc. technologies.
- So there is no need to write too much code. It hides the basic steps of these technologies.
2. Loose Coupling :
- The spring applications are loosely coupled because of dependency injection.
3. Easy to test:
- The Dependency Injection makes easier to test the application.
- The EJB or Struts application require server to run the application but spring framework doesn't require
server.
4. Light weight:
- Spring framework is lightweight because of its POJO implementation.
- The Spring Framework doesn't force the programmer to inherit any class or implement any interface.
- That is why it is said non-invasive.
5. Fast Development:
- The Dependency Injection feature of Spring Framework and it support to various frameworks makes the
easy development of JavaEE application.
6. Powerful abstraction:
- It provides powerful abstraction to JavaEE specifications such as JMS, JDBC, JPA and JTA.
7. Declarative support :
- It provides declarative support for caching, validation, transactions and formatting.

Question 2: Explain Spring Module.

Answer:

- The spring framework comprises of many modules such as core, beans, context, expression language, AOP,
Aspects, Instrumentation, JDBC, ORM, OXM, JMS, Transaction, Web, Servlet, and Struts etc.
- These modules are grouped into Test, Core Container,
AOP, Aspects, Instrumentation, Data Access / Integration,
Web (MVC / Remoting) as displayed in the following diagram.

1
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

Core Container:
The Core Container consists of the Core, Beans, Context, and Expression Language modules whose detail is as follows:

- The Core module provides the fundamental parts of the framework, including the IoC and Dependency Injection
features.
- The Bean module provides Bean Factory which is a sophisticated implementation of the factory pattern.
- The Context module builds on the solid base provided by the Core and Beans modules and it is a medium to
access any objects defined and configured. The Application Context interface is the focal point of the Context
module.
- TheSpEL module provides a powerful expression language for querying and manipulating an object graph at
runtime.

Data Access/Integration:
The Data Access/Integration layer consists of the JDBC, ORM, OXM, JMS and Transaction modules whose detail is as
follows:

- The JDBC module provides a JDBC-abstraction layer that removes the need to do tedious JDBC related coding.
- The ORM module provides integration layers for popular object-relational mapping APIs, including JPA, JDO,
Hibernate, and iBatis.
- The OXM module provides an abstraction layer that supports Object/XML mapping implementations for JAXB,
Castor, XMLBeans, JiBX and XStream.
- The Java Messaging Service JMS module contains features for producing and consuming messages.
- The Transaction module supports programmatic and declarative transaction management for classes that
implement special interfaces and for all your POJOs.

Web:
The Web layer consists of the Web, Web-MVC, Web-Socket, and Web-Portlet modules whose detail is as follows:

- The Web module provides basic web-oriented integration features such as multipart file-upload functionality
and the initialization of the IoC container using servlet listeners and a web-oriented application context.
- The Web-MVC module contains Spring's model-view-controller (MVC) implementation for web applications.
- The Web-Socket module provides support for WebSocket-based, two-way communication between client and
server in web applications.
- The Web-Portlet module provides the MVC implementation to be used in a portlet environment and mirrors
the functionality of Web-Servlet module.

Miscellaneous:
There are few other important modules like AOP, Aspects, Instrumentation, Web and Test modules whose detail is
as follows:

- The AOP module provides aspect-oriented programming implementation allowing you to define method-
interceptors and pointcuts to cleanly decouple code that implements functionality that should be separated.
- The Aspects module provides integration with AspectJ which is again a powerful and mature aspect oriented
programming (AOP) framework.

2
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

- The Instrumentation module provides class instrumentation support and class loader implementations to be
used in certain application servers.
- The Messaging module provides support for STOMP as the WebSocket sub-protocol to use in applications. It
also supports an annotation programming model for routing and processing STOMP messages from WebSocket
clients.
- The Test module supports the testing of Spring components with JUnit or TestNG frameworks.

Question 3: Explain Constructor Injection.

Answer:

- All the three attributes are set thru constructor injection.


- The toString() method of the User bean class is overridden to display the user object.
- Here the beans.xml file is used to do spring bean configuration.
- Constructor-based DI is accomplished when the container invokes a class constructor with a number of
arguments, each representing a dependency on other class.
- Let's see the simple example to inject primitive and string-based values.
- We have created three files here:
1. Employee.java
2. ApplicationContext.xml
3. Test.java

Employee.java

- It is a simple class containing two fields’ id and name.


- There are four constructors and one method in this class.
package com.javatpoint;
public class Employee {
private int id;
private String name;
public Employee() {System.out.println("def cons");}
public Employee(int id) {this.id = id;}
public Employee(String name) { this.name = name;}
public Employee(int id, String name) {
this.id = id;
this.name = name;
}

void show(){
System.out.println(id+" "+name);
}
}

ApplicationContext.xml

- We are providing the information into the bean by this file.


- The constructor-arg element invokes the constructor.

3
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

- In such case, parameterized constructor of int type will be invoked.


- The value attribute of constructor-arg element will assign the specified value.
- The type attribute specifies that int parameter constructor will be invoked.

<?xml version="1.0" encoding="UTF-8"?>


<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="e" class="com.javatpoint.Employee">
<constructor-arg value="10" type="int"></constructor-arg>
</bean>
</bean>

Test.java

- This class gets the bean from the applicationContext.xml file and calls the show method.

package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class Test {


public static void main(String[] args) {
Resource r=new ClassPathResource("applicationContext.xml");
BeanFactory factory=new XmlBeanFactory(r);
Employee s=(Employee)factory.getBean("e");
s.show();

Question 4: Explain CI dependent object.

Answer:

- If there is HAS-A relationship between the classes, we create the instance of dependent object (contained
object) first then pass it as an argument of the main class constructor.
- Here, our scenario is Employee HAS-A Address.
- The Address class object will be termed as the dependent object.
- In the constructor injection, the dependency injection will be injected with the help of constructors.
- Now to set the dependency injection as constructor dependency injection(CDI) in bean, it is done through the
bean-configuration file for this, the property to be set with the constructor dependency injection is declared
under the <constructor-arg> tag in the bean-config file.

4
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

Question 5: Explain CI with collection.

Answer:

- We can inject collection values by constructor in spring framework.


- There can be used three elements inside the constructor-arg element. It can be:
1. list
2. set
3. Map
- Each collection can have string based and non-string based values.
- In the Constructor Injection, the dependency injection will be injected with the help of constructors.
- Now to set the dependency injection as constructor dependency injection (CDI) in bean, it is done through
the bean-configuration file for this, the property to be set with the constructor dependency injection is
declared under the <constructor-arg> tag in the bean-config file.

Question 6: Explain CI with map.

Answer:

- we are using map as the answer that have answer with posted username.
- Here, we are using key and value pair both as a string

Question 7: Explain CI inheriting bean.

Answer:

- By using the parent attribute of bean, we can specify the inheritance relation between the beans.
- In such case, parent bean values will be inherited to the current bean.
- bean inheritance allows for reusing configuration from a parent bean and customizing it in child beans.
- This feature helps in reducing redundancy and managing configurations more efficiently
- Unlike Java class inheritance, Spring bean inheritance is more about configuration inheritance rather than
code inheritance.
- Constructor arguments, property values, and container-specific information like initialization method, static
factory method name, and so on may all be found in a bean definition.
- A parent definition’s configuration data is passed down to a child bean definition.
- The child definition can override or add values as needed.

Question 8: Explain Setter Injection.

Answer:

- We can inject the dependency by setter method also.


- The subelement of is used for setter injection.
- Here we are going to inject
1. primitive and String-based values
2. Dependent object (contained object)
3. Collection values etc.
- We have created three files here:
1. Employee.java
2. applicationContext.xml
3. Test.java
5
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

1. Employee.java
- It is a simple class containing three fields id, name and city with its setters and getters and a method to display
these information’s.

package com.javatpoint;
public class Employee {
private int id;
private String name;
private String city;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;

void display(){

System.out.println(id+" "+name+" "+city);

2. applicationContext.xml
- We are providing the information into the bean by this file.
- The property element invokes the setter method.
- The value subelement of property will assign the specified value.

<?xml version="1.0" encoding="UTF-8"?>

<beans

xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

6
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

xmlns:p="http://www.springframework.org/schema/p"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="obj" class="com.javatpoint.Employee">

<property name="id">

<value>20</value>

</property>

<property name="name">

<value>Arun</value>

</property>

<property name="city">

<value>ghaziabad</value>

</property>

</bean>

</beans>

3. Test.java
- This class gets the bean from the applicationContext.xml file and calls the display method.

package com.javatpoint;

import org.springframework.beans.factory.BeanFactory;

import org.springframework.beans.factory.xml.XmlBeanFactory;

import org.springframework.core.io.*;

public class Test {

public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");

BeanFactory factory=new XmlBeanFactory(r);

Employee e=(Employee)factory.getBean("obj");

s.display();

}
7
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

Question 9: Explain SI dependent Object.

Answer:

- If there is HAS-A relationship between the classes, we create the instance of dependent object (contained
object) first then pass it as an argument of the main class constructor.
- Here, our scenario is Employee HAS-A Address.
- The Address class object will be termed as the dependent object.
- If there exists a relationship between the classes of our spring application, then we create the instance of the
dependent object also called the contained object.
- After creating the instance of the dependent object we pass it as an argument of the main class container.

Question 10: Explain SI With Collection.

Answer:

- We can inject collection values by setter method in spring framework.


- There can be used three elements inside the property element.
- It can be:
1. list
2. set
3. map
- Each collection can have string based and non-string based value.
- Dependency Injection is the main functionality provided by Spring IOC(Inversion of Control).
- The Spring-Core module is responsible for injecting dependencies through either Constructor or Setter
methods.
- In Setter Dependency Injection(SDI) the dependency will be injected with the help of setters and getters
methods.
- A bean-configuration file is used to set DI as SDI in the bean.
- For this, the property to be set with the SDI is declared under the <property> tag in the bean-config file.

Question 11: Explain SI with Map.

Answer:

- we are using map as the answer for a question that have answer as the key and username as the value.
- Here, we are using key and value pair both as a string.

Question 12: Explain Difference Between CI and SI

Answer:

No Setter Injection Constructor Injection

1. In Setter Injection, partial injection of dependencies In constructor injection, partial injection of dependencies
can possible, means if we have 3 dependencies like cannot possible, because for calling constructor we must
int, string, long, then its not necessary to inject all pass all the arguments right, if not so we may get error
values if we use setter injection. If you are not
injecting it will take default values for those
primitives

8
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

2. Setter Injection will override the constructor But constructor injection cannot overrides the setter
injection value, provided if we write setter and injected values
constructor injection for the same property [I
already told regarding this, hope you remember]

3. If we have more dependencies for example 15 to In this case, Constructor injection is highly recommended, as
20 are there in our bean class then, in this case we can inject all the dependencies within 3 to 4 lines [I
setter injection is not recommended as we need to mean, by calling one constructor]
write almost 20 setters right, bean length will
increase.

4. Setter injection makes bean class object as mutable Constructor injection makes bean class object as immutable
[We can change] [We cannot change]

Question 13: Explain Auto Wiring.

Answer:

-Autowiring by property name.


-Spring container looks at the properties of the beans on which autowire attribute is set to byName in the XML
configuration file.
- It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
- Autowiring by property datatype.
 Advantage of Autowiring
- It requires the less code because we don't need to write the code to inject the dependency explicitly.
 Disadvantage of Autowiring
- No control of programmer.
- It can't be used for primitive and string values.
 Autowiring Modes:
- There are many autowiring modes.

NO Mode Description

1. no It is the default autowiring mode. It means no autowiringbydefault.

2. byName The byName mode injects the object dependency according to name of the bean. In such case,
property name and bean name must be same. It internally calls setter method.

3. byType The byType mode injects the object dependency according to type. So property name and bean
name can be different. It internally calls setter method

4. constructor The constructor mode injects the dependency by calling the constructor of the class. It calls the
constructor having large number of parameters.

5. autodetect It is deprecated since Spring 3

9
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

Question 14: Explain Factory Method.

Answer:

- Spring framework provides facility to inject bean using factory method.


- To do so, we can use two attributes of bean element.
- factory-method: represents the factory method that will be invoked to inject the bean.
- factory-bean: represents the reference of the bean by which factory method will be invoked. It is used if factory
method is non-static.
- A method that returns instance of a class is called factory method.

public class A {

public static A getA(){//factory method

return new A();

 Factory Method Types

There can be three types of factory method:

1) A static factory method that returns instance of its own class. It is used in singleton design pattern.
- <bean id="a" class="com.javatpoint.A" factory-method="getA"></bean>
2) A static factory method that returns instance of another class. It is used instance is not known and decided at
runtime.
- <bean id="b" class="com.javatpoint.A" factory-method="getB"></bean>
3) A non-static factory method that returns instance of another class. It is used instance is not known and decided
at runtime.
- <bean id="a" class="com.javatpoint.A"></bean>
- <bean id="b" class="com.javatpoint.A" factory-method="getB" factory-bean="a"></bean>

Question 15: Explain AOP Terminology.

Answer:

- One of the key components of Spring Framework is the Aspect oriented programming (AOP) framework.
- Aspect Oriented Programming entails breaking down program logic into distinct parts called socalled concerns.
The functions that span multiple points of an application are called cross-cutting
- conceptually separate from the application's business logic.
- There are various common good examples of aspects like logging, security, and caching etc.
- The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.
 AOP Terminologies:
- Before we start working with AOP, let us become familiar with the AOP concepts and terminology.
- These terms are not specific to Spring, rather they are related to AOP.
Sr no Terms Description

1. Aspect A module which has a set of APIs providing cross-cutting requirements. For example, a
10
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

logging module would be called AOP aspect for logging. An application can have any
number of aspects depending on the requirement.

2. Join point This represents a point in your application where you can plug-in AOP aspect. You can
also say, it is the actual place in the application where an action will be taken using
Spring AOP framework.

3. Advice This is the actual action to be taken either before or after the method execution. This
is actual piece of code that is invoked during program execution by Spring AOP
framework.

4. Pointcut This is a set of one or more points where an advice should be executed. You can
specify pointcuts using expressions or patterns as we will see in our AOP examples.

5. Introduction An introduction allows you to add new methods or attributes to existing classes.

6. Target object The object being advised by one or more aspects, this object will always be a pointed
object. Also referred to as the advised object

 Aspects Implementation
- These two approaches have been explained in detail in the following two sub chapters

Sr No Approach Description

1. XML Schema based Aspects are implemented using regular classes along with XML based
configuration.

2. @AspectJ based @AspectJ refers to a style of declaring aspects as regular Java classes
annotated with Java 5 annotations.

 Pointcut
- A pointcut defines at what joinpoints, the associated Advice should be applied. Advice can be applied at any
joinpoint supported by the AOP framework.
- Pointcuts allow you to specify where you want your advice to be applied. Often you specify these pointcuts
using explicit class and method names or through regular expressions that define matching class and method
name patterns.
- Some AOP frameworks allow you to create dynamic pointcuts that determine whether to apply advice based on
runtime decisions, such as the value of method parameters.

11
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

 Advices
- Join point: a point during the execution of a program, such as the execution of a method or the handling of an
exception. In Spring AOP, a join point always represents a method execution. Advice: action taken by an aspect
at a particular join.

Question 16: Explain Spring with Hibernate.

Answer.

- Spring is one of the most used Java EE Framework and Hibernate is the most popular ORMframework. That’s
why Spring Hibernate combination is used a lot in enterprise applications.
- We can simply integrate hibernate application with spring application.
- In hibernate framework, we provide all the database information hibernate.cfg.xml file.But if we are going to
integrate the hibernate application with spring, we don't need to create the hibernate.cfg.xml file. We can
provide all the information in the applicationContext.xml file.
 Advantage of Spring framework with hibernate
- The Spring framework provides HibernateTemplate class, so you don't need to follow so many steps like create
Configuration, BuildSessionFactory, Session, beginning and committing transaction etc.
- So, it saves a lot of code.
 Methods of HibernateTemplate class

Sr No Method Description

1. void persist(Object entity) persists the given object.

2. Serializable save(Object entity) persists the given object and returns id

3. void saveOrUpdate(Object entity) persists or updates the given object. If id is found, it updates the record
otherwise saves the record.

4. void update(Object entity) updates the given object.

5. void delete(Object entity) deletes the given object on the basis of id.

Question 17: Explain Spring with JPA.

Answer:

- Spring Data JPA API provides JpaTemplate class to integrate spring application with JPA.
- JPA (Java Persistent API) is the sun specification for persisting objects in the enterprise application.
- It is currently used as the replacement for complex entity beans.
- The implementation of JPA specification are provided by many vendors such as:
1. Hibernate
2. Toplink
3. iBatis
4. OpenJPAetc

12
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

 Advantage of Spring JpaTemplate


-You don't need to write the before and after code for persisting, updating, deleting or searching object such as
creating Persistence instance, creating EntityManagerFactory instance, creating EntityTransaction instance,
creating EntityManager instance, commitingEntityTransaction instance and closing EntityManager.
- So, it saves a lot of code.
 Example

Account .java

public class Account {

private int accountNumber;

private String owner;

private double balance;

//no-arg and parameterized constructor

//getters and setters

Question 18: Explain Spring Expression Language (SPEL).

Answer:

1. SPEL
2. SPEL API
3. Hello SPEL Example
4. Other Examples of SPEL
- SpEL is an exression language supporting the features of querying and manipulating an object graph at runtime.
- There are many expression languages available such as JSP EL, OGNL, MVEL and JBoss EL.
- SpEL provides some additional features such as method invocation and string templating functionality
 Operators in SPEL
- We can use many operators in SpEL such as arithmetic, relational, logical etc. There are given a lotof examples
of using different operators in SpEL.
- he expression language supports the following functionality
1. Literal expressions
2. Boolean and relational operators
3. Regular expressions
4. Class expressions
5. Accessing properties, arrays, lists, maps
6. Method invocation
7. Relational operators
8. Assignment
9. Ternary operator
10. Variables

13
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

 Variable in SPEL

1. Using Variable in SPEL

2. StandardEvaluationContext class

3. Example of Using variable in SPEL

- In SpEL, we can store a value in the variable and use the variable in the method and call the method. To work on
variable, we need to useStandardEvaluationContext class.
 Example

Calculation.java

public class Calculation {

private int number;

public int getNumber() {

return number;

public void setNumber(int number) {

this.number = number;

public int cube(){

return number*number*number;

Question 19: Explain Spring and RMI Integration.

Answer:

1. Spring and RMI Integration


2. Example of Spring and RMI Integration
- Spring RMI lets you expose your services through the RMI infrastructure.
- Spring provides an easy way to run RMI application by the help of
org.springframework.remoting.rmi.RmiProxyFactoryBean and
org.springframework.remoting.rmi.RmiServiceExporter classes.
- Spring RMI integration in Java is a way to provide remote method invocation (RMI) support to Spring
applications.
- In this integration, Spring acts as a client and a server using RMI for communication.
- In this article, we will learn about how to integrate spring and RMI in java.

14
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

- Here are the step-by-step guides to integrate Spring and RMI in Java, along with sample code snippets.
 Example

Calculation.java

public interface Calculation {

int cube (int number);

Question 20: Explain HTTP Invoker Example.

Answer:

1. Spring Remoting by HTTP Invoker


2. Example of Spring HTTP Invoker
- Spring provides its own implementation of remoting service known asHttpInvoker.
- It can be used for http request than RMI and works well across the firewall.
- By the help of HttpInvokerServiceExporter and HttpInvokerProxyFactoryBean classes, we can implement the
remoting service provided by Spring's Http Invokers
 Http Invoker Vs RMI
- RMI uses JRMP protocol whereas Http Invokes uses HTTP protocol.
- Since enterprise applications mostly use http protocol, it is the better to use HTTP Invoker. RMI also has some
security issues than HTTP Invoker.
- HTTP Invoker works well across firewalls.
 Calculation.java
public interface Calculation {
int cube(int number);
}

Question 21: Explain Hessian.

Answer:

- By the help of HessianServiceExporter and HessianProxyFactoryBeanclasses, we can implement the remoting


service provided by hessian.
 Advantage of Hessian
- Hessian works well across firewall. Hessian is portable to integrate with other languages such as PHP and .Net.

 hessian-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd">

15
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

<bean id="calculationBean" class="com.as.CalculationImpl"></bean>

<bean name="/Calculation.http"

class="org.springframework.remoting.caucho.HessianServiceExporter">

<property name="service" ref="calculationBean"></property>

<property name="serviceInterface" value="com.javatpoint.Calculation"></property>

</bean>

</beans>

Question 22: Explain Burlap.

Answer:

- Both, Hessian and Burlap are provided by Coucho. Burlap is the xml-based alternative of Hessian.
- By the help of BurlapServiceExporter and BurlapProxyFactoryBeanclasses, we can implement the remoting
service provided by burlap.
 burlap-servlet.xml
- It must be created inside the WEB-INF folder. Its name must be servletname-servlet.xml.
- It defines bean for CalculationImplandBurlapServiceExporter.

<?xml version="1.0" encoding="UTF-8"?>


<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">

<bean id="calculationBean" class="com.javatpoint.CalculationImpl"></bean>


<bean name="/Calculation.http"
class="org.springframework.remoting.caucho.BurlapServiceExporter">
<property name="service" ref="calculationBean"></property>
<property name="serviceInterface" value="com.javatpoint.Calculation"></property>
</bean>
</beans>

Question 23: Explain Spring and JAXB.

Answer:

- JAXB is an acronym for Java Architecture for XML Binding.


- It allows java developers to map Java class to XML representation. JAXB can be used to marshal java objects into
XML and vice-versa.
- It is an OXM (Object XML Mapping) or O/M framework provided by Sun.
 Advantage of JAXB
- No need to create or use a SAX or DOM parser and write callback methods.

16
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

Question 24: Explain Spring with Xstream.

Answer:

- Xstream is a library to serialize objects to xml and vice-versa without requirement of any mapping file. Notice
that castor requires an mapping file.
- XStreamMarshaller class provides facility to marshal objects into xml and vice-versa.

Example

 Employee.java

public class Employee {

private int id;

private String name;

private float salary;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public float getSalary() {

return salary;

public void setSalary(float salary) {

this.salary = salary;

17
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

 Beans.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="xstreamMarshallerBean" class="org.springframework.oxm.xstream.XStreamMarshaller">

<property name="annotatedClasses" value="com.javatpoint.Employee"></property>

</bean>

</beans>

 Client.java

public class Client{

public static void main(String[] args)throws IOException{

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

Marshaller marshaller = (Marshaller)context.getBean("xstreamMarshallerBean");

Employee employee=new Employee();

employee.setId(10);

employee.setName("Raj Pandya");

employee.setSalary(100000);

marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml")));

System.out.println("XML Created Sucessfully");

Question 25: Explain Spring with Castor.

Answer:

- By the help of CastorMarshaller class, we can marshal the java objects into xml and vice-versa using castor.
- It is the implementation class for Marshaller and Unmarshaller interfaces.
- It doesn’t require any further configuration bydefault.

18
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

- Ease of configuration. Spring's bean factory makes it easy to configure marshallers, without needing to
construct JAXB context, JiBX binding factories, etc.
- Consistent Interfaces. Spring's O/X mapping operates through two global interfaces: the Marshaller and
Unmarshaller interface.
- These abstractions allow you to switch O/Xmapping frameworks with relative ease, with little or no changes
required on the classes that do the marshalling.
 Consistent Exception Hierarchy.
- Spring provides a conversion from exceptions from the underlying O/X mapping tool to its own exception
hierarchy with the XmlMappingExceptionas theroot exception.
- As can be expected, these runtime exceptions wrap the original exception so no information is lost.
 Example

Employee.java

public class Employee {

private int id;

private String name;

private float salary;

public int getId() {

return id;

public void setId(int id) {

this.id = id;

public String getName() {

return name;

public void setName(String name) {

this.name = name;

public float getSalary() {

return salary;

public void setSalary(float salary) {

19
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

this.salary = salary;

 Beans.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="castorMarshallerBean" class="org.springframework.oxm.castor.CastorMarshaller">

<property name="targetClass" value="com.as.Employee"></property>

<property name="mappingLocation" value="mapping.xml"></property>

</bean>

</beans>

 Mapping.xml

<?xml version="1.0"?>

<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version


1.0//EN""http://castor.org/mapping.dtd">

<mapping>

<class name="com.as.Employee" auto-complete="true" >

<map-to xml="Employee" ns-uri="http://www.javatpoint.com" ns-prefix="dp"/>

<field name="id" type="integer">

<bind-xml name="id" node="attribute"></bind-xml>

</field>

<field name="name">

<bind-xml name="name"></bind-xml>

</field>

20
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

<field name="salary">

<bind-xml name="salary" type="float"></bind-xml>

</field>

</class>

</mapping>

 Client.java
public class Client{
public static void main(String[] args)throws IOException{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Marshaller marshaller = (Marshaller)context.getBean("castorMarshallerBean");

Employee employee=new Employee();


employee.setId(101);
employee.setName("Virajjoshi");
employee.setSalary(100000);
marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml")));
System.out.println("XML Created Sucessfully");

Question 26: Explain Spring and Struts 2.

Answer:

- Spring is a popular web framework that provides easy integration with lots of common web tasks.
- So the question is, why do we need Spring when we have Struts2? Well, Spring is more than a MVC framework -
it offers many other goodies which are not available in Struts. For example: dependency injection that can be
useful to any framework. In this chapter, we will go through a simple example to see how to integrate Spring
and Struts2 together.
- Spring framework provides an easy way to manage the dependency.
- It can be easily integrated with struts 2 framework.
- The ContextLoaderListener class is used to communicate spring application with struts 2.
- It must be specified in the web.xml file
 Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID"version="3.0">
21
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

<display-name>Struts 2</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>

<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>

<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
 User.java

publicclassUser{

privateStringfirstName;

privateStringlastName;

publicString execute()

return"success";

publicStringgetFirstName(){

returnfirstName;

publicvoidsetFirstName(StringfirstName){

22
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

this.firstName=firstName;

publicStringgetLastName(){

returnlastName;

publicvoidsetLastName(StringlastName){

this.lastName=lastName;

Question 27: Explain Hibernate.

Answer:

- Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open-source persistent
framework created by Gavin King in 2001. It is a powerful, high-performance Object-Relational Persistence and
Query service for any Java Application.
- Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve the
developer from 95% of common data persistence related programming tasks.
- Hibernate sits between traditional Java objects and database server
to handle all the work in persisting those objects based on the
appropriate O/R mechanisms and patterns.

 Needs of Hibernate: -
- Hibernate takes care of mapping Java classes to database tables using XML files and without writing any line of
code. Provides simple APIs for storing and retrieving Java objects directly to and from the database.
- If there is change in Database or in any table then the only need to change XML file properties.
- Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
- Hibernate does not require an application server to operate.
- Manipulates Complex associations of objects of your database.
- Minimize database access with smart fetching strategies.
- Provides Simple querying of data.

23
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

 Hibernate Advantages:
There are many advantages of Hibernate Framework. They are as follows:
1) Opensource and Lightweight:
- Hibernate framework is opensource under the LGPL license and lightweight.
2) Fast performance:
- The performance of hibernate framework is fast because cache is internally used in hibernate
framework.
- There are two types of cache in hibernate framework first level cache and second level cache.
First level cache is enabled bydefault.
3) Database Independent query:
- HQL (Hibernate Query Language) is the object-oriented versionof SQL.
- It generates the database independent queries.
4) Automatic table creation:
- Hibernate framework provides the facility to create the tables of the database automatically.
- So there is no need to create tables in the database manually.
5) Simplifies complex join:
- To fetch data form multiple tables is easy in hibernate framework.
6) Provides query statistics and database status:
- Hibernate supports Query cache and provide statistics about query and database status.
 Hibernate Disadvantages:
- Its saying hibernate is little slower than pure JDBC.
- There is one major disadvantage, which was boilerplate code issue, actually we need to write same code in
several files in the same application, but spring eliminated this.

Question 28: Explain Hibernate Architecture.

Answer:

- The Hibernate architecture includes many objects persistent object, session factory, transaction factory,
connection factory, session, transaction etc.
- There are 4 layers in hibernate architecture java application layer, hibernate framework layer, backhand api
layer and database layer.
- Let's see the diagram of hibernate architecture.
 Elements of Hibernate Architecture:
- For creating the first hibernate application, we must know the elements of Hibernate architecture.
- They are as follows:
1. SessionFactory
- The SessionFactory is a factory of session and client of ConnectionProvider.
- It holds second level cache (optional) of data.
- The org.hibernate.SessionFactory interface provides factory method to get the object of Session.
2. Session
- The session object provides an interface between the application and data stored in the database. It
isshort-lived object and wraps the JDBC connection.
- It is factory of Transaction, Query and Criteria. It holds afirst-level cache (mandatory) of data.

24
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

3. Transaction
- The transaction object specifies the atomic unit of work. It is optional.
- The org.hibernate.Transaction interface provides methods for transaction management.
4. ConnectionProvider
- It is a factory of JDBC connections.
- It abstracts the application from DriverManager or DataSource.
- It is optional.
5. TransactionFactory
- It is a factory of Transaction. It is optional.

Question 29: Explain Hibernate with Annotation.

Answer:

- The hibernate application can be created with annotation.


- There are many annotations that can be used to create hibernate application such as @Entity, @Id, @Table etc.
- Hibernate Annotations are based on the JPA 2 specification and supports all the features.
- All the JPA annotations are defined in the javax.persistence.* package. Hibernate EntityManager implements
the interfaces and life cycle defined by the JPA specification.
- The core advantage of using hibernate annotation is that you don't need to create mapping (hbm) file.
- Here, hibernate annotations are used to provide the meta data.
 There are 4 steps to create the hibernate application with annotation.
1. Add the jar file for MySQL and annotation
2. Create the Persistent class
3. Add mapping of Persistent class in configuration file
4. Create the class that retrieves or stores the persistent object
 Employee.java
package com.example;
import javax.persistence.*;

@Entity
@Table(name="employee")
25
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

public class Employee


{
@Id @GeneratedValue
@Column(name="id")
private int id;
@Column(name="firstname")
private String firstname;
@Column(name="lastname")
private String lastname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
}

InsertDB.java
package com.example;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class InsertDB {
public static void main(String[] args)
{
try
{
Configuration config = new Configuration();
//AnnotationConfiguration config =
//new AnnotationConfiguration();
config.configure();
SessionFactory factory = config.buildSessionFactory();
26
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

Session session = factory.openSession();


Transaction tr = session.beginTransaction();
Employee e1 =new Employee();
e1.setFirstname("Ashish");
e1.setLastname("Patel");
session.save(e1);
tr.commit();
session.close();
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}

SelectDB.java

package com.example;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

public class SelecetDB

public static void main(String[] args)

try

Configuration config = new Configuration();

config.configure();

SessionFactory factory = config.buildSessionFactory();

Session session = factory.openSession();

Employee e1 = (Employee)session.

load(Employee.class, 1);

27
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

System.out.println(e1.getId());

System.out.println(e1.getFirstname());

System.out.println(e1.getLastname());

session.close();

catch(Exception e)

System.out.println(e.getMessage());

 Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/company</property>

<property name="hibernate.connection.username">root</property>

<property name="hibernate.connection.password"></property>

<property name="hibernate.show_sql">true</property>

<mapping class="com.example.Employee"/>

</session-factory>

</hibernate-configuration>

28
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

Question 30: Explain Hibernate Web Application.

Answer:

- Here, we are going to create a web application with hibernate. For creating the web application, we are using
JSP for presentation logic, Bean class for representing data and DAO class for database codes.
- As we create the simple application in hibernate, we don't need to perform any extra operations in hibernate
for creating web application. In such case, we are getting the value from the user using the JSP file.
 Example to create web application using hibernate
- In this example, we are going to insert the record of the user in the database. It is simply a registration form.
1. Hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

<session-factory>

<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<property name="hibernate.connection.url">jdbc:mysql://localhost:3309/abhishek</property>

<property name="hibernate.connection.username">root</property>

<property name="hibernate.connection.password">root</property>

<property name="hibernate.show_sql">true </property>

` <mapping resource="user.hbm.xml"/>

</session-factory>

</hibernate-configuration>
2. User.hbm.xml

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>

29
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

<class name="com.example.User" table="user" catalog="abhishek">

<id name="id" type="java.lang.Integer">

<column name="id" />

<generator class="identity" />

</id>

<property name="name" type="string">

<column name="name" length="45" not-null="true" />

</property>

<property name="password" type="string">

<column name="password" length="45" not-null="true" />

</property>

<property name="email" type="string">

<column name="email" length="45" not-null="true" />

</property>

</class>

</hibernate-mapping>

3.User.java

package com.example;
public class User
{

private int id;


private String name,password,email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {

30
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}

4.UserDAO.java

package com.example;

import org.hibernate.*;

import org.hibernate.cfg.*;

public class UserDAO

public static int register(User u)

int i=0;

try

Configuration config = new Configuration();

config.configure();

SessionFactory factory = config.buildSessionFactory();

Session session= factory.openSession();

Transaction t=session.beginTransaction();

t.begin();

31
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

i=(Integer)session.save(u);

t.commit();

session.close();

return i;

catch(Exception e)

System.out.println("Message "+e.getMessage());

return i;

5. Index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"

pageEncoding="ISO-8859-1"%>

<html>

<body>

<form action="register.jsp" method="post">

Name:<input type="text" name="name"/><br><br/>

Password:<input type="password" name="password"/><br><br/>

Email ID:<input type="text" name="email"/><br><br/>

<input type="submit" value="register"/>

</form>

</body>

</html>

6. Register.jsp

<%@page import="com.example.UserDAO"%>

32
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

<jsp:useBean id="obj" class="com.example.User">

<jsp:setProperty property="*" name="obj"/>

</jsp:useBean>

<%

try

int i=UserDAO.register(obj);

if(i>0)

out.println("You are successfully registered");

else

out.println("You are not registered");

catch(Exception e)

out.println(e.getMessage());

%>

Question 31: Explain Hibernate Generator classes.

Answer:

- The <generator>subelement of id used to generate the unique identifier for the objects of persistent class.
- There are many generator classes defined in the Hibernate Framework.All the generator classes implements the
org.hibernate.id.IdentifierGenerator interface.
- The application programmer may create one's own generator classes by implementing the IdentifierGenerator
interface.
- Hibernate framework provides many built-in generator classes:
1. Assigned
- It is the default generator strategy if there is no <generator> element. In this case, application assigns the
id.
- For example:
....
<hibernate-mapping>
<class ...>

33
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

<id ...>
<generator class="assigned"></generator>
</id>
.....
</class>
</hibernate-mapping>
2. Increment
- It generates the unique id only if no other process is inserting data into this table.
- It generates short, int or long type identifier. The first generated identifier is 1 normally and incremented
as 1.
- Syntax:
....
<hibernate-mapping>
<class ...>
<id ...>
<generator class="increment"></generator>
</id>
.....
</class>
</hibernate-mapping>
3. Sequence
- It uses the sequence of the database.
- if there is no sequence defined, it creates a sequenceautomatically e.g. in case of Oracle database.
- Syntax:

.....

<id ...>

<generator class="sequence"></generator>

</id>

.....

For defining your own sequence, use the param subelement of generator.

.....

<id ...>

<generator class="sequence">

<param name="sequence">your_sequence_name</param>

</generator>

34
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

4. Hilo
- It uses high and low algorithm to generate the id of type short, int and long.
- Syntax:
.....
<id ...>
<generator class="hilo"></generator>
</id>
.....
5. Native
- It uses identity, sequence or hilo depending on the database vendor.
- Syntax:
.....
<id ...>
<generator class="native"></generator>
</id>
.....
6. Identity
- It is used in Sybase, My SQL, MS SQL Server, DB2 and HypersonicSQL to support the id column.
- The returned id is of type short, int or long.
7. Seqhilo
- It uses high and low algorithm on the specified sequence name. The returned id is of type short, int or
long.
8. Uuid
- It uses 128-bit UUID algorithm to generate the id. The returned id is of type String, unique within a
network (because IP is used). The UUID is represented in hexadecimal digits, 32 in length.
9. Guid
- It uses GUID generated by database of type string. It works on MS SQL Server and MySQL.
10. Select
- It uses the primary key returned by the database trigger.
11. Foreign
- It uses the id of another associated object, mostly used with <one-to-one> association.
12. sequence-identity
- It uses a special sequence generation strategy. It is supported in Oracle 10g drivers only.

Question 32: Explain SQL Dialects in Hibernate.

Answer:

- For connecting any hibernate application with the database, you must specify the SQL dialects.
- There are many Dialects classes defined for RDBMS in the org.hibernate.dialect package.
- They are as follows:
NO RDBMS Dialect

1 Oracle (any version) org.hibernate.dialect.OracleDialect

35
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

2 Oracle9i org.hibernate.dialect.Oracle9iDialect

3 Oracle10g org.hibernate.dialect.Oracle10gDialect

4 MySQL org.hibernate.dialect.MySQLDialect

5 MySQL with InnoDB org.hibernate.dialect.MySQLInnoDBDialect

6 MySQL with MyISAM org.hibernate.dialect.MySQLMyISAMDialect

7 DB2 org.hibernate.dialect.DB2Dialect

8 DB2 AS/400 org.hibernate.dialect.DB2400Dialect

9 DB2 OS390 org.hibernate.dialect.DB2390Dialect

10 Microsoft SQL Server org.hibernate.dialect.SQLServerDialect

11 Sybase org.hibernate.dialect.SybaseDialect

12 Sybase Anywhere org.hibernate.dialect.SybaseAnywhereDialect

13 PostgreSQL org.hibernate.dialect.PostgreSQLDialect

14 SAP DB org.hibernate.dialect.SAPDBDialect

15 Informix org.hibernate.dialect.InformixDialect

16 HypersonicSQL org.hibernate.dialect.HSQLDialect

17 Ingres org.hibernate.dialect.IngresDialect

18 Progress org.hibernate.dialect.ProgressDialect

19 Mckoi SQL org.hibernate.dialect.MckoiDialect

20 Interbase org.hibernate.dialect.InterbaseDialect

21 Pointbase org.hibernate.dialect.PointbaseDialect

22 FrontBase org.hibernate.dialect.FrontbaseDialect

23 Firebird org.hibernate.dialect.FirebirdDialect

Question 33: Explain Hibernate Log4.

Answer:

- log4j is a reliable, fast and flexible logging framework (APIs) written in Java, which is distributed under
the Apache Software License.
- log4j is a popular logging package written in Java.
- log4j has been ported to the C, C++, C#, Perl, Python, Ruby, and Eiffel languages.

36
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

- log4j is highly configurable through external configuration files at runtime. It views the logging process
in terms of levels of priorities and offers mechanisms to direct logging information to a great variety of
destinations, such as a database, file, console, UNIX Syslog, etc.
- log4j has three main components
1. loggers:
- Responsible for capturing logging information.
2. appenders:
- Responsible for publishing logging information to various preferred destinations.
3. layouts:
- Responsible for formatting logging information in different styles.
- log4j API package is distributed under the Apache Software License, a full-fledged open-source
license certified by the open-source initiative.
- The latest log4j version, including full-source code, class files and documentation can be found
at http://logging.apache.org/log4j/.

 History of log4j
- Started in early 1996 as tracing API for the E.U. SEMPER (Secure Electronic Marketplace for
Europe)project.
- After countless enhancements and several incarnations, the initial API has evolved to become log4j, a
popular logging package for Java.
- The package is distributed under the Apache Software License, a full-fledged open-source license certified
by the open-source initiative.
- The latest log4j version, including its full-source code, class files, and documentation can be found at
http://logging.apache.org/log4j/.
 log4j Features
- It is thread-safe.
- It is optimized for speed.
- It is based on a named logger hierarchy.
- It supports multiple output appenders per logger.
37
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

- It supports internationalization.
- It is not restricted to a predefined set of facilities.
- Logging behavior can be set at runtime using a configuration file.
- It is designed to handle Java Exceptions from the start.
- It uses multiple levels, namely ALL, TRACE, DEBUG, INFO, WARN, ERROR and FATAL.
- The format of the log output can be easily changed by extending theLayout class.
- The target of the log output as well as the writing strategy can be altered by implementations of the
Appender interface.
- It is fail-stop. However, although it certainly strives to ensure delivery, log4j does not guarantee that
each log statement will be delivered to its destination.

Question 34: Explain Logging Methods.

Answer:

- Once we obtain an instance of a named logger, we can use several methods of the logger to log messages.
- The Logger class has the following methods for printing the logging information.

Sr.No Methods and Description

1 public void debug(Object message)


It prints messages with the level Level.DEBUG.

2 public void error(Object message)


It prints messages with the level Level.ERROR.

3 public void fatal(Object message);


It prints messages with the level Level.FATAL.

4 public void info(Object message);


It prints messages with the level Level.INFO.

5 public void warn(Object message);


It prints messages with the level Level.WARN.

6 public void trace(Object message);


It prints messages with the level Level.TRACE

Question 35: Explain Inheritance Mapping.

Answer:

- Java is an object oriented language. It is possible to implement Inheritance in Java.


- Inheritance isone of the most visible facets of Object-relational mismatch.
- Object oriented systems can model both “is a” and “has a” relationship. Relational model supports only “has a”
relationship between two entities.
- Hibernate can help you map such Objects with relational tables.
38
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

- But you need to choose certain mapping strategy based on your needs.
- It is possible to use different mapping strategies for different branches of the same inheritance hierarchy.
- You can then make use of implicit polymorphism to achieve polymorphism across the whole hierarchy.
- We can map the inheritance hierarchy classes with the table of the database.
- There are threinheritance mapping strategies defined in the hibernate:
1. Table Per Hierarchy
2. Table Per Concrete class
3. Table Per Subclass
1. Table Per Hierarchy
- In table per hierarchy mapping, single table is required to map the whole hierarchy, an extra column (known
as discriminator column) is added to identify the class. But nullable values are stored in the table.
- Table Per Hierarchy using xml file
- Table Per Hierarchy using Annotation
2. Table Per Concrete class
- In case of table per concrete class, tables are created as per class. But duplicate column is added in subclass
tables.
- Table Per Concrete class using xml file
- Table Per Concrete class using Annotation
3. Table Per Subclass
- In this strategy, tables are created as per class but related by foreign key. So, there are no duplicate columns.
- Table Per Subclass using xml file
- Table Per Subclass using Annotation

Question 36: Explain Collection Mapping in Hibernate.

Answer:

- We can use map collection elements of Persistent class in Hibernate.


- You need to declare the type of collection in Persistent class from one of the following types:
1. java.util.List
2. java.util.Set
3. java.util.SortedSet
4. java.util.Map
5. java.util.SortedMap
6. java.util.Collection
7. or write the implementation of org.hibernate.usertype.UserCollectionType

- The persistent class should be defined like this for collection element.

- package com.javatpoint;
import java.util.List;
public class Question {
private int id;
private String qname;
private List<String> answers;//List can be of any type
//getters and setters
}

39
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

 Mapping collection in mapping file


- There are many subelements of <class> elements to map the collection.
- They are <list>, <bag>, <set> and <map>.
 There are three subelements used in the list:
1. <key> element is used to define the foreign key in this table based on the Question class identifier.
2. <index> element is used to identify the type. List and Map are indexed collection.
3. <element> is used to define the element of the collection. This is the mapping of collection if collection stores
string objects. But if collection stores entity reference (another class objects), we need to define <one-to-many>
or <many-to-many> element.

Question 37: Explain Collection Elements.

Answer:

- The collection elements can have value or entity reference (another class object).
- We can use one ofthe 4 elements
1. Element
2. component-element
3. one-to-many, or
4. many-to-many
- The element and component-element are used for normal value such as string, int etc.
- whereas one-to-many and many-to-many are used to map entity reference.
1. One to Many by List using XML
- If the persistent class has list object that contains the entity reference, we need to use one-to-
many association to map the list element.
- Here, we are using the scenario of Forum where one question has multiple answers.
2. One to Many by List using Annotation
- In this section, we will perform one-to-many association to map the list object of persistent class
using annotation.
- Here, we are using the scenario of Forum where one question has multiple answers.
3. Mapping Bag of One-to-Many using XML
- A Bag is a java collection that stores elements without caring about the sequencing but allow
duplicate elements in the list.
- A bag is a random grouping of the objects in the list.
- A Collection is mapped with a <bag> element in the mapping table and initialized with
java.util.ArrayList.
4. One-to-Many by Set using XML
- A Set is a java collection that does not contain any duplicate element.
- More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one
null element.
- So objects to be added to a set must implement both the equals() and hashCode() methods so that
Java can determine whether any two elements/objects are identical.
- A Set is mapped with a <set> element in the mapping table and initialized withjava.util.HashSet.
- You can use Set collection in your class when there is no duplicate element required in the
collection.

40
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

5. Many-to-Many by Map using XML


- A Map is a java collection that stores elements in key-value pairs and does not allow duplicate
elements in the list.
- The Map interface provides three collection views, which allow a map's contents to be viewed as a
set of keys, collection of values, or set of key-value mappings.
- A Map is mapped with a <map> element in the mapping table and an unordered map can be
initialized with java.util.HashMap.

Question 38: Explain Component Mapping and Association Mapping.

Answer:

1. Component Mapping
- In component mapping, we will map the dependent object as a component.
- A component is an object that is stored as a value rather than entity reference.
- This is mainly used if the dependent object doesn’t have primary key.
- It is used in case of composition (HAS-A relation), that is why it is termed as component.
- A Component mapping is a mapping for a class having a reference to another class as a member variable.
- We have seen such mapping while having two tables and using element in the mapping file.
2. Association Mapping
- The mapping of associations between entity classes and the relationships between tables is the soul
of ORM.
- Following are the four ways in which the cardinality of the relationship between the objects can be
expressed.
- An association mapping can be unidirectional as well as bidirectional.
- Entities can contain references to other entities, either directly as an embedded property or field,or
indirectly via a collection of some sort (arrays, sets, lists, etc.).
- These associations are represented using foreign key relationships in the underlying tables.
- These foreign keys will rely on the identifiers used by participating tables.
- In hibernate mapping associations, one (and only one) of the participating classes is referred to as
“managing the relationship” and other one is called “managed by” using ‘mappedBy’ property. We
should not make both ends of association “managing the relationship”. Never do it.

Question 39: Explain Hibernate Transaction Management.

Answer:

- A transaction simply represents a unit of work.


- In such case, if one step fails, the whole transaction fails (which is termed as atomicity).
- A transaction can be described by ACID properties (Atomicity, Consistency, Isolation and Durability).
 Transaction Interface in Hibernate
- In hibernate framework, we have Transaction interface that defines the unit of work.
- It maintains abstraction from the transaction implementation (JTA,JDBC).
- A transaction is associated with Session and instantiated by calling session.beginTransaction().
- The methods of Transaction interface are as follows:
1. void begin() starts a new transaction.
2. void commit() ends the unit of work unless we are in FlushMode.NEVER.
41
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

3. void rollback() forces this transaction to rollback.


4. void setTimeout(int seconds) it sets a transaction timeout for any transaction started by a subsequent call to
begin on this instance.
5. boolean isAlive() checks if the transaction is still alive.
6. void registerSynchronization(Synchronization s) registers a user synchronization callback for this transaction.
7. boolean wasCommited() checks if the transaction is commited successfully.
8. boolean wasRolledBack() checks if the transaction is rolledback successfully.

Question 40: Explain Hibernate Query Language (HQL).

Answer:

-
Hibernate Query Language (HQL) is same as SQL (Structured Query Language) but it doesn't depends on the
table of the database.
- Instead of table name, we use class name in HQL.
- So it is database independent query language.
 Advantage of HQL:
- There are many advantages of HQL. They are as follows:
1. database independent
2. supports polymorphic queries
3. easy to learn for Java Programmer
 Query Interface
- It is an object oriented representation of Hibernate Query.
- The object of Query can be obtained by calling the createQuery() method Session interface.
- The query interface provides many methods. There is given commonly used methods:
1. public int executeUpdate() is used to execute the update or delete query.
2. public List list() returns the result of the ralation as a list.
3. public Query setFirstResult(int rowno) specifies the row number from where record will be retrieved.
4. public Query setMaxResult(int rowno) specifies the no. of records to be retrieved from the relation (table).
5. public Query setParameter(int position, Object value) it sets the value to the JDBC style query parameter.
6. public Query setParameter(String name, Object value) it sets the value to a named query parameter.
 Advantage of HCQL
- The HCQL provides methods to add criteria, so it is easy for the java programmer to add criteria.
- The java programmer is able to add many criteria on a query.
 Hibernate Named Query
- The hibernate named query is way to use any query by some meaningful name.
- It is like using alias names.
- The Hibernate framework provides the concept of named queries so that application programmer need not to
scatter queries to all the java code.
- There are two ways to define the named query in hibernate:
1. by annotation
2. by mapping file.
 Hibernate Named Query by annotation
- If you want to use named query in hibernate, you need to have knowledge of @NamedQueries and
@NamedQuery annotations.
- @NameQueries annotation is used to define the multiple named queries.
- @NameQuery annotation is used to define the single named query.

42
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA

- Let's see the example of using the named queries:


@NamedQueries(
{
@NamedQuery(
name = "findEmployeeByName",
query = "from Employee e where e.name = :name"
)

 Hibernate Named Query by mapping file


- If want to define named query by mapping file, you need to use query element of hibernatemapping to define
the named query.
 Caching in Hibernate Hibernate
- caching improves the performance of the application by pooling the object in the cache.
- There are mainly two types of caching:
1. first level cache
2. second level cache.
1. First Level Cache
- Session object holds the first level cache data. It is enabled by default.
- The first level cache data will not be available to entire application.
- An application can use many session object.
2. Second Level Cache
- SessionFactory object holds the second level cache data.
- The data stored in the second level cache will be available to entire application.
- But we need to enable it explicitely.
 Hibernate Second Level Cache
- Hibernate second level cache uses a common cache for all the session object of a session factory. It is useful if
you have multiple session objects from a session factory.
- SessionFactory holds the second level cache data. It is global for all the session objects and not enabled by
default.
- Different vendors have provided the implementation of Second Level Cache.
1. EH Cache
2. OS Cache
3. Swarm Cache
4. JBoss Cache
- Each implementation provides different cache usage functionality.
- There are four ways to use second level cache.
1. read-only: caching will work for read only operation.
2. nonstrict-read-write: caching will work for read and write but one at a time.
3. read-write: caching will work for read and write, can be used simultaneously.
4. transactional: caching will work for transaction.

43

You might also like