Application Development Using Advance Java
Application Development Using Advance Java
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.
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.
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.
Answer:
Employee.java
void show(){
System.out.println(id+" "+name);
}
}
ApplicationContext.xml
3
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA
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.*;
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
Answer:
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
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.
Answer:
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(){
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.
<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">
<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.*;
Employee e=(Employee)factory.getBean("obj");
s.display();
}
7
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA
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.
Answer:
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.
Answer:
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]
Answer:
NO Mode Description
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.
9
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA
Answer:
public class A {
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>
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.
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
3. void saveOrUpdate(Object entity) persists or updates the given object. If id is found, it updates the record
otherwise saves the record.
5. void delete(Object entity) deletes the given object on the basis of id.
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
Account .java
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
2. StandardEvaluationContext class
- 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
return number;
this.number = number;
return number*number*number;
Answer:
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
Answer:
Answer:
hessian-servlet.xml
<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 name="/Calculation.http"
class="org.springframework.remoting.caucho.HessianServiceExporter">
</bean>
</beans>
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.
Answer:
16
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA
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
return id;
this.id = id;
return name;
this.name = name;
return 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>
</beans>
Client.java
employee.setId(10);
employee.setName("Raj Pandya");
employee.setSalary(100000);
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
return id;
this.id = id;
return name;
this.name = name;
return salary;
19
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA
this.salary = salary;
Beans.xml
<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>
</beans>
Mapping.xml
<?xml version="1.0"?>
<mapping>
</field>
<field name="name">
<bind-xml name="name"></bind-xml>
</field>
20
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA
<field name="salary">
</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");
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;
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.
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.
Answer:
@Entity
@Table(name="employee")
25
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA
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
SelectDB.java
package com.example;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
try
config.configure();
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
"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
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
"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>
` <mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
2. User.hbm.xml
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
29
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA
</id>
</property>
</property>
</property>
</class>
</hibernate-mapping>
3.User.java
package com.example;
public class User
{
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.*;
int i=0;
try
config.configure();
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
pageEncoding="ISO-8859-1"%>
<html>
<body>
</form>
</body>
</html>
6. Register.jsp
<%@page import="com.example.UserDAO"%>
32
M.Sc. (IT & CA) (Semester – 1) ADVANCE JAVA
</jsp:useBean>
<%
try
int i=UserDAO.register(obj);
if(i>0)
else
catch(Exception e)
out.println(e.getMessage());
%>
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.
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
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
7 DB2 org.hibernate.dialect.DB2Dialect
11 Sybase org.hibernate.dialect.SybaseDialect
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
20 Interbase org.hibernate.dialect.InterbaseDialect
21 Pointbase org.hibernate.dialect.PointbaseDialect
22 FrontBase org.hibernate.dialect.FrontbaseDialect
23 Firebird org.hibernate.dialect.FirebirdDialect
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.
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.
Answer:
- 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
Answer:
- 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
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
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.
Answer:
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
43