Cb3303 Notes Unit 5
Cb3303 Notes Unit 5
Before Spring
Java Beans, POJO
Lacked in Security and Transaction Management
Then came enterprise java beans EJB
o Solved Transaction processing
o Session Processing
o EJB development was not easy
o Spring Emerged as answer
Introduction to Spring
Spring is an open-source lightweight framework , main technologies used by Spring
Framework for developing enterprise applications
Aspect-Oriented Programming AOP
o Enables cross-cutting concerns in a centralized area
POJO
Dependency Injection DI
o Java enterprise edition specification
Spring is widely used for creating scalable applications. For web applications Spring provides
Spring MVC which is a widely used module of spring which is used to create scalable web
applications.
But main disadvantage of spring projects is that configuration is really time-consuming and
can be a bit overwhelming for the new developers. Making the application production-ready
takes some time if you are new to the spring.
Page 1
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Solution to this is Spring Boot. Spring Boot is built on the top of the spring and contains all
the features of spring. And is becoming favourite of developer’s these days because of it’s a
rapid production-ready environment which enables the developers to directly focus on the
logic instead of struggling with the configuration and set up.
Spring Boot is a microservice-based framework and making a production-ready application
in it takes very less time.
Spring Boot Architecture
To understand the architecture of Spring Boot, let us first see different layers and classes
present in it.
Layers in Spring Boot: There are four main layers in Spring Boot:
Presentation Layer: As the name suggests, it consists of views(i.e. frontend
part)
Data Access Layer: CRUD (create, retrieve, update, delete) operations on the
database comes under this category.
Service Layer: This consist of service classes and uses services provided by
data access layers.
Integration Layer: It consists of web different web services(any service
available over the internet and uses XML messaging system).
Then we have utility classes, validator classes and view classes.
All the services provided by the classes are implemented in their corresponding
classes and are retrieved by implementing the dependency on those interfaces.
Since Spring boot uses all the features/modules of spring-like Spring data, Spring
MVC etc. so the architecture is almost the same as spring MVC, except for the fact
that there is no need of DAO and DAOImpl classes in Spring boot.
Creating a data access layer needs just a repository class instead which is
implementing CRUD operation containing class.
A client makes the https request(PUT/GET)
Page 2
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Then it goes to controller and the controller mapped with that route as that of request
handles it, and calls the service logic if required.
Business logic is performed in the service layer which might be performing the logic
on the data from the database which is mapped through JPA with model/entity class
Finally, a JSP page is returned in the response if no error occurred.
Setup Spring Boot:
Setup Java JDK from Oracle’s official site.
Download and Setup STS(Spring Tools Suite).
Start a new spring starter project
Click on File -> New -> Spring starter project
Fill the appropriate details and add dependency and finish.
Edit the application properties.
Run the main file as a Java application.
Generally, to develop a Spring Boot Application we choose Eclipse, Spring Tool
Suite, and IntelliJ IDEA IDE.
Create a Spring Boot Project in Eclipse IDE
The Eclipse IDE is famous for the Java Integrated Development Environment (IDE), but ithas
a number of pretty cool IDEs, including the C/C++ IDE, JavaScript/TypeScript IDE, PHP IDE,
and more.
Procedure:
1. Install Eclipse IDE for Enterprise Java and Web Developer
2. Create a Spring Boot Project in Spring Initializr
3. Import Spring Boot Project in Eclipse IDE
4. Search “maven” and choose Existing Maven Project
5. Choose Next
6. Click on the Browse button and select the extracted zip
7. Click on the Finish button and we are done creating the Spring Boot project
Let us discuss these steps in detail alongside visual aids
Step 1: Install Eclipse IDE for Enterprise Java and Web Developer
Please refer to this article How to Install Eclipse IDE for Enterprise Java and Web
Development and install the Eclipse IDE.
Step 2: Create a Spring Boot Project in Spring Initializr
Go to this link and create a Spring Boot project. Please fill in all the details accordingly and
at last click on the GENERATE button below. This will download your Spring Boot project
in zip format. Now extract the folder into your local machine.
Page 3
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 4
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Step 4: Search “maven” and choose Existing Maven Project and click on the Next button as
shown in the below image.
Step 5: Now click on the Browse button and select the extracted zip file that has been
generated.
Page 5
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Step 6. And at last click on the Finish button and we are done creating the Spring Boot
project
By now, Spring Boot project has been created as depicted in the below media
Page 6
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 7
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Step 3: In this pop-up window fill the detail below as follows and further click on
the Next button as shown in the below image.
Service URL: Default
As your need
Group: A unique base name of the company or group that created the project
Artifact: A unique name of the project
package name
Step 4: Choose your required Spring Boot Version and select your dependencies as per your
project requirement. And at last click on the Next button.
Page 8
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 9
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Here now, please wait for some time to download all the required files such as dependencies
that you have selected in Step4 above.
Below is the Welcome screen after you have successfully Created and Setup Spring Boot
Project in Spring Tool Suite
Page 10
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 11
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 12
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 13
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
By now, the Spring Boot project has been created as depicted in the below media. The left
side contains the Project file structure while in the middle you can see the Code Editor is
present.
Page 14
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
After downloading, extract the zip file. It contains a bin folder, in which spring setup is
stored. We can use it to execute Spring Boot application.
CLI executes groovy files. So, first, we need to create a groovy file for Spring Boot
application.
Open terminal and cd into the bin location of cli folder.
Page 15
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 16
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
This project is running on the port 8080. So, we can invoke it on any browser by using the
following url.
1. localhost:8080:/cli-example
It will produce the following output.
Spring Annotations
Spring Annotations are a form of metadata that provides data about a program. Annotations
are used to provide supplemental information about a program. It does not have a direct effect
on the operation of the code they annotate. It does not change the action of the compiled
program.
Types of Spring Framework Annotations
Basically, there are 6 types of annotation available in the whole spring framework.
1. Spring Core Annotations
2. Spring Web Annotations
3. Spring Boot Annotations
4. Spring Scheduling Annotations
Page 17
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
DI-Related Annotations
@Autowired
@Qualifier
@Primary
@Bean
@Lazy
@Required
@Value
@Scope
@Lookup, etc.
Context Configuration Annotations
@Profile
@Import
@ImportResource
@PropertySource, etc.
A DI (Dependency Injection) Related Annotations
1.1 : @Autowired
@Autowired annotation is applied to the fields, setter methods, and constructors. It injects
object dependency implicitly. We use @Autowired to mark the dependency that will be
injected by the Spring container.
1.2 : Field injection
Java
class Student {
@Autowired
Page 18
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Address address;
class Student {
Address address;
@Autowired
Student(Address address) {
this.address = address;
}
}
class Student {
Address address;
@Autowired
void setaddress(Address address) {
this.address = address;
}
Page 19
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@RequestMapping
@RequestBody
@PathVariable
@RequestParam
Response Handling Annotations
@ResponseBody
@ExceptionHandler
@ResponseStatus
@Controller
@RestController
@ModelAttribute
@CrossOrigin
Example: @Controller
package com.example.demo.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
Page 20
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@Controller
public class DemoController {
@RequestMapping("/hello")
@ResponseBody
public String helloGFG()
{
return "Hello GeeksForGeeks";
}
}
Type 3: Spring Boot Annotations
Spring annotations present in
the org.springframework.boot.autoconfigure and
org.springframework.boot.autoconfigure.condition packages are commonly known as
Spring Boot annotations. Some of the annotations that are available in this category are:
@SpringBootApplication
@EnableAutoConfiguration
Auto-Configuration Conditions
@ConditionalOnClass, and @ConditionalOnMissingClass
@ConditionalOnBean, and @ConditionalOnMissingBean
@ConditionalOnProperty
@ConditionalOnResource
@ConditionalOnWebApplication and @ConditionalOnNotWebApplication
@ConditionalExpression
@Conditional
Example: @SpringBootApplication
This annotation is used to mark the main class of a Spring Boot application. It encapsulates
@Configuration, @EnableAutoConfiguration, and @ComponentScan annotations with their
default attributes.
Java
Page 21
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@SpringBootApplication
// Class
public class DemoApplication {
SpringApplication.run(DemoApplication.class, args);
}
}
Type 4: Spring Scheduling Annotations
Spring annotations present in the org.springframework.scheduling.annotation packages
arecommonly known as Spring Scheduling annotations. Some of the annotations that are
available in this category are:
@EnableAsync
@EnableScheduling
@Async
@Scheduled
@Schedules
Example: @EnableAsync
Spring Data provides an abstraction over data storage technologies. Hence the business logic
code can be much more independent of the underlying persistence implementation. Some of
the annotations that are available in this category are:
Common Spring Data Annotations
Page 22
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@Transactional
@NoRepositoryBean
@Param
@Id
@Transient
@CreatedBy, @LastModifiedBy, @CreatedDate, @LastModifiedDate
Spring Data JPA Annotations
@Query
@Procedure
@Lock
@Modifying
@EnableJpaRepositories
Spring Data Mongo Annotations
@Document
@Field
@Query
@EnableMongoRepositories
Example:
A @Transactional
When there is a need to configure the transactional behavior of a method, we can do it with
@Transactional annotation.
@Transactional
void payment() {}
B @Id: @Id marks a field in a model class as the primary key. Since it’s implementation-
independent, it makes a model class easy to use with multiple data store engines.
class Student {
@Id
Long id;
// other fields
Page 23
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
// ...........
}
Type 6: Spring Bean Annotations
There’re several ways to configure beans in a Spring container. You can declare them using
XML configuration or you can declare beans using the @Bean annotation in a configuration
class or you can mark the class with one of the annotations from
the org.springframework.stereotype package and leave the rest to component
scanning.Some of the annotations that are available in this category are:
@ComponentScan
@Configuration
Stereotype Annotations
@Component
@Service
@Repository
@Controller
Example: Stereotype Annotations
Spring Framework provides us with some special annotations. These annotations are used to
create Spring beans automatically in the application context. @Component annotation is the
main Stereotype Annotation. There are some Stereotype meta-annotations which is derived
from @Component those are
1. @Service
2. @Repository
3. @Controller
1: @Service: We specify a class with @Service to indicate that they’re holding the business
logic. Besides being used in the service layer, there isn’t any other special use for this
annotation. The utility classes can be marked as Service classes.
2: @Repository: We specify a class with @Repository to indicate that they’re dealing
with CRUD operations, usually, it’s used with DAO (Data Access Object) or Repository
implementations that deal with database tables.
3: @Controller: We specify a class with @Controller to indicate that they’re front
controllers and responsible to handle user requests and return the appropriate response. It is
mostly used with REST Web Services.
So the stereotype annotations in spring are @Component, @Service, @Repository,
and@Controller.
Page 24
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@SpringBootApplication
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
Auto-Configuration Conditions
@ConditionalOnClass, and @ConditionalOnMissingClass
@ConditionalOnBean, and @ConditionalOnMissingBean
@ConditionalOnProperty
@ConditionalOnResource
@ConditionalOnWebApplication and @ConditionalOnNotWebApplication
@ConditionalExpression
@Conditional
1. @SpringBootApplication Annotation
This annotation is used to mark the main class of a Spring Boot application. It
encapsulates @SpringBootConfiguration, @EnableAutoConfiguration, and
@ComponentScan annotations with their default attributes.
Page 25
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Example:
Java
@SpringBootApplication
// Class
public class DemoApplication {
SpringApplication.run(DemoApplication.class, args);
}
}
2. @SpringBootConfiguration Annotation
It is a class-level annotation that is part of the Spring Boot framework. It implies that a class
provides Spring Boot application configuration. It can be used as an alternative to Spring’s
standard @Configuration annotation so that configuration can be found automatically. Most
Spring Boot Applications use @SpringBootConfiguration via @SpringBootApplication. If an
application uses @SpringBootApplication, it is already using @SpringBootConfiguration.
Example:
Page 26
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Java
@SpringBootConfiguration
public class Application {
SpringApplication.run(Application.class, args);
@Bean
public StudentService studentService() {
return new StudentServiceImpl();
3.}@EnableAutoConfiguration Annotation
This annotation auto-configures the beans that are present in the classpath. It simplifies the
developer’s work by assuming the required beans from the classpath and configure it to run
the application. This annotation is part of the spring boot framework. For example, when we
illustrate the spring-boot-starter-web dependency in the classpath, Spring boot auto-
configures Tomcat, and Spring MVC. The package of the class declaring the
@EnableAutoConfiguration annotation is considered as the default. Therefore, we need to
apply the @EnableAutoConfiguration annotation in the root package so that every sub-
packages and class can be examined.
Example:
Java
@Configuration
@EnableAutoConfiguration
public class Application {
SpringApplication.run(Application.class, args);
Page 27
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
4. @ComponentScan Annotation
@ComponentScan tells Spring in which packages you have annotated classes that should be
managed by Spring. So, for example, if you have a class annotated with @Controller which is
in a package that is not scanned by Spring, you will not be able to use it as a Spring
controller. So we can say @ComponentScan enables Spring to scan for things like
configurations, controllers, services, and other components that are defined. Generally,
@ComponentScan annotation is used with @Configuration annotation to specify the package
for Spring to scan for components.
Example:
Java
@Configuration
@ComponentScan
// Main class
public class Application {
SpringApplication.run(Application.class, args);
}
}
5. @ConditionalOnClass Annotation and @ConditionalOnMissingClass Annotation
@ConditionalOnClass Annotation used to mark auto-configuration bean if the class in the
annotation’s argument is present/absent.
Example:
Java
Page 28
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@Configuration
@ConditionalOnClass(MongoDBService.class)
class MongoDBConfiguration {
@Bean
@ConditionalOnMissingBean(type = "JpaTransactionManager")
JpaTransactionManager jpaTransactionManager(
EntityManagerFactory entityManagerFactory)
{
// Insert code here
}
7. @ConditionalOnProperty Annotation
These annotations are used to let configuration be included based on the presence and value
of a Spring Environment property.
Example:
Java
@Bean
@ConditionalOnProperty(name = "usemongodb",
havingValue = "local")
Page 29
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
DataSource
dataSource()
{
// Insert code here
}
@Bean
@ConditionalOnProperty(name = "usemongodb",
havingValue = "prod")
DataSource
dataSource()
{
// Insert code here
}
8. @ConditionalOnResource Annotation
These annotations are used to let configuration be included only when a specific resource is
present in the classpath.
Example:
Java
@ConditionalOnResource(resources
= "classpath:mongodb.properties")
Properties
additionalProperties()
{
// Insert code here
}
9. @ConditionalOnExpression Annotation
Page 30
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
These annotations are used to let configuration be included based on the result of a
SpEL(Spring Expression Language) expression.
Example:
Java
@Bean
@ConditionalOnExpression("${env} && ${havingValue == 'local'}")
DataSource dataSource()
{
// Insert code here
@Configuration
@ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)
{
// Insert code here
Page 31
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 32
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Jetty Server
The Spring Boot also supports an embedded server called Jetty Server. It is an HTTP server
and Servlet container that has the capability of serving static and dynamic content. It is used
when machine to machine communication is required.
If we want to add the Jetty server in the application, we need to add the spring-boot-
starter-jetty dependency in our pom.xml file.
Remember: While using Jetty server in the application, make sure that the default Tomcat
server is excluded from the spring-boot-starter-web. It avoids the conflict between servers.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
Page 33
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<groupId>org.springframework.boot</groupId>
Page 34
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
We can also customize the behavior of the Jetty server by
usingthe application.properties file.
Undertow Server
Spring Boot provides another server called Undertow. It is also an embedded web server like
Jetty. It is written in Java and manage and sponsored by JBoss. The main advantages of
Undertow server are:
o Supports HTTP/2
o HTTP upgrade support
o Websocket Support
o Provides support for Servlet 4.0
o Flexible
o Embeddable
Remember: While using Undertow server in the application, make sure that the default
Tomcat server is excluded from the spring-boot-starter-web. It avoids the conflict between
servers.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
Page 35
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
o core
o el
o logging
o websocket
The starter-tomcat has the following dependencies:
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>8.5.23</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-el</artifactId>
<version>8.5.23</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.apache.tomcat.embed</groupId>
Page 36
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<artifactId>tomcat-embed-websocket</artifactId>
Page 37
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<version>8.5.23</version>
<scope>compile</scope>
</dependency>
We can also use spring-mvc without using the embedded Tomcat server. If we want to do so,
we need to exclude the Tomcat server by using the <exclusion> tag, as shown in the
following code.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
Spring Boot AOP
The application is generally developed with multiple layers. A typical Java application has
the following layers:
o Web Layer: It exposes the services using the REST or web application.
o Business Layer: It implements the business logic of an application.
o Data Layer: It implements the persistence logic of the application.
The responsibility of each layer is different, but there are a few common aspects that apply
toall layers are Logging, Security, validation, caching, etc. These common aspects are
If we implement these concerns in each layer separately, the code becomes more difficult to
maintain. To overcome this problem, Aspect-Oriented Programming (AOP) provides a
solution to implement cross-cutting concerns.
o Implement the cross-cutting concern as an aspect.
o Define pointcuts to indicate where the aspect has to be applied.
It ensures that the cross-cutting concerns are defined in one cohesive code component.
Page 38
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
AOP
AOP (Aspect-Oriented Programming) is a programming pattern that increases modularity
by allowing the separation of the cross-cutting concern. These cross-cutting concerns are
different from the main business logic. We can add additional behavior to existing code
without modification of the code itself.
Spring's AOP framework helps us to implement these cross-cutting concerns.
Using AOP, we define common functionality in one place. We are free to define how and
where this functionality is applied without modifying the class to which we are applying the
new feature. The cross-cutting concern can now be modularized into special classes,
called aspect.
There are two benefits of aspects:
o First, the logic for each concern is now in one place instead of scattered all over the
codebase.
o Second, the business modules only contain code for their primary concern. The
secondary concern has been moved to the aspect.
The aspects have the responsibility that is to be implemented, called advice. We can
implement an aspect's functionality into a program at one or more join points.
Benefits of AOP
o It is implemented in pure Java.
o There is no requirement for a special compilation process.
o It supports only method execution Join points.
o Only run time weaving is available.
o Two types of AOP proxy is available: JDK dynamic proxy and CGLIB proxy.
Cross-cutting concern
The cross-cutting concern is a concern that we want to implement in multiple places in an
application. It affects the entire application.
AOP Terminology
o Aspect: An aspect is a module that encapsulates advice and pointcuts and
provides cross-cutting An application can have any number of aspects. We can
implement an aspect using regular class annotated with @Aspect annotation.
o Pointcut: A pointcut is an expression that selects one or more join points where
advice is executed. We can define pointcuts using expressions or patterns. It uses
different kinds of expressions that matched with the join points. In Spring
Framework, AspectJ pointcut expression language is used.
Page 39
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
o Join point: A join point is a point in the application where we apply an AOP aspect.
Or it is a specific execution instance of an advice. In AOP, join point can be a method
execution, exception handling, changing object variable value, etc.
o Advice: The advice is an action that we take either before or after the method
execution. The action is a piece of code that invokes during the program execution.
There are five types of advices in the Spring AOP framework: before, after, after-
returning, after-throwing, and around advice. Advices are taken for a
particular join point. We will discuss these advices further in this section.
o Target object: An object on which advices are applied, is called the target object.
Target objects are always a proxied It means a subclass is created at run time in
which the target method is overridden, and advices are included based on their
configuration.
o Weaving: It is a process of linking aspects with other application types. We can
perform weaving at run time, load time, and compile time.
Proxy: It is an object that is created after applying advice to a target object is called proxy.
The Spring AOP implements the JDK dynamic proxy to create the proxy classes with target
classes and advice invocations. These are called AOP proxy classes.
AOP vs. OOP
The differences between AOP and OOP are as follows:
AOP OOP
Aspect: A code unit that encapsulates Class: A code unit that encapsulates
pointcuts, advices, and attributes. methods and attributes.
Pointcut: It defines the set of entry points Method signature: It defines the entry
in which advice is executed. points for the execution of method bodies.
Page 40
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 41
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
After Throwing Advice: An advice that executes when a join point throws an exception.
After Returning Advice: An advice that executes when a method executes successfully.
Before implementing the AOP in an application, we are required to add Spring
AOP dependency in the pom.xml file.
Spring Boot Starter AOP
Spring Boot Starter AOP is a dependency that provides Spring AOP and AspectJ. Where
AOP provides basic AOP capabilities while the AspectJ provides a complete AOP
framework.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
HIBERNATE
Hibernate is an Object-Relational Mapping (ORM) solution for JAVA. It is 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 relieves the developer from 95% of common data persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the works in
persisting those objects based on the appropriate O/R mechanisms and patterns.
Hibernate Advantages
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 the database or in any table, then you need to change the XML
file properties only.
Page 42
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Abstracts away the unfamiliar SQL types and provides a way to work around familiar
Java Objects.
Hibernate does not require an application server to operate.
Manipulates Complex associations of objects of your database.
Minimizes database access with smart fetching strategies.
Provides simple querying of data.
Supported Databases
Hibernate supports almost all the major RDBMS. Following is a list of few of the database
engines supported by Hibernate −
HSQL Database Engine
DB2/NT
MySQL
PostgreSQL
FrontBase
Oracle
Microsoft SQL Server Database
Sybase SQL Server
Informix Dynamic Server
Supported Technologies
Hibernate supports a variety of other technologies, including −
XDoclet Spring
J2EE
Eclipse plug-ins
Maven
Hibernate has a layered architecture which helps the user to operate without having to know
the underlying APIs. Hibernate makes use of the database and configuration data to provide
persistence services (and persistent objects) to the application.
Following is a very high level view of the Hibernate Application Architecture.
Page 43
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Following is a detailed view of the Hibernate Application Architecture with its important
core classes.
Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java
Naming and Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of
functionality common to relational databases, allowing almost any database with a JDBC
driver to be supported by Hibernate. JNDI and JTA allow Hibernate to be integrated with
J2EE application servers.
Page 44
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Following section gives brief description of each of the class objects involved in Hibernate
Application Architecture.
Configuration Object
The Configuration object is the first Hibernate object you create in any Hibernate application.
It is usually created only once during application initialization. It represents a configuration
or properties file required by the Hibernate.
The Configuration object provides two keys components −
Database Connection − This is handled through one or more configuration files
supported by Hibernate. These files are hibernate.properties and hibernate.cfg.xml.
Class Mapping Setup − This component creates the connection between the Java
classes and database tables.
SessionFactory Object
Configuration object is used to create a SessionFactory object which in turn configures
Hibernate for the application using the supplied configuration file and allows for a Session
object to be instantiated. The SessionFactory is a thread safe object and used by all the
threads of an application.
The SessionFactory is a heavyweight object; it is usually created during application start up
and kept for later use. You would need one SessionFactory object per database using a
separate configuration file. So, if you are using multiple databases, then you would have to
create multiple SessionFactory objects.
Session Object
A Session is used to get a physical connection with a database. The Session object is
lightweight and designed to be instantiated each time an interaction is needed with the
database. Persistent objects are saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually
thread safe and they should be created and destroyed them as needed.
Transaction Object
A Transaction represents a unit of work with the database and most of the RDBMS supports
transaction functionality. Transactions in Hibernate are handled by an underlying transaction
manager and transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface,
instead managing transactions in their own application code.
Query Object
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the
database and create objects. A Query instance is used to bind query parameters, limit the
number of results returned by the query, and finally to execute the query.
Page 45
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Criteria Object
Criteria objects are used to create and execute object oriented criteria queries to retrieve
objects.
First Hibernate Example without IDE
1. Steps to create first Hibernate Application
1. Create the Persistent class
2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application without IDE
Here, we are going to create the first hibernate application without IDE. For creating the first
hibernate application, we need to follow the following steps:
1. Create the Persistent class
2. Create the mapping file for Persistent class
3. Create the Configuration file
4. Create the class that retrieves or stores the persistent object
5. Load the jar file
6. Run the first hibernate application by using command prompt
1) Create the Persistent class
A simple Persistent class should follow some rules:
o A no-arg constructor: It is recommended that you have a default constructor at least
package visibility so that hibernate can create the instance of the Persistent class by
newInstance() method.
o Provide an identifier property: It is better to assign an attribute as id. This attribute
behaves as a primary key in database.
o Declare getter and setter methods: The Hibernate recognizes the method by getter
and setter method names by default.
o Prefer non-final class: Hibernate uses the concept of proxies, that depends on the
persistent class. The application programmer will not be able to use proxies for lazy
association fetching.
Page 46
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
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;
}
Page 47
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 48
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
Page 49
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
4) Create the class that retrieves or stores the object
In this class, we are simply storing the employee object to the database.
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
Page 50
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
import
org.hibernate.boot.Metadata;
Page 51
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
Page 52
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 53
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Create the java project by File Menu - New - project - java project . Now specify the
project name e.g. firsthb then next - finish .
To add the jar files Right click on your project - Build path - Add external archives. Now
select all the jar files as shown in the image given below then click open.
In this example, we are connecting the application with oracle database. So, you must add the
ojdbc14.jar file.
download the ojdbc14.jar file
3) Create the Persistent class
Here, we are creating the same persistent class which we have created in the previous topic.
To create the persistent class, Right click on src - New - Class - specify the class with
package name (e.g. com.javatpoint.mypackage) - finish .
Page 54
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Employee.java
package com.javatpoint.mypackage;
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;
}
}
4) Create the mapping file for Persistent class
Here, we are creating the same mapping file as created in the previous topic. To create the
mapping file, Right click on src - new - file - specify the file name (e.g. employee.hbm.xml)
Page 55
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 56
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp1000">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="firstName"></property>
<property name="lastName"></property>
</class>
</hibernate-mapping>
5) Create the Configuration file
The configuration file contains all the informations for the database such as connection_url,
driver_class, username, password etc. The hbm2ddl.auto property is used to create the table
in the database automatically. We will have in-depth learning about Dialect class in next
topics. To create the configuration file, right click on src - new - file. Now specify the
configuration file name e.g. hibernate.cfg.xml.
hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<hibernate-configuration>
<session-factory>
Page 57
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">oracle</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
6) Create the class that retrieves or stores the persistent object
In this class, we are simply storing the employee object to the database.
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import
org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
{
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();
Page 58
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 59
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
session.save(e1);
t.commit();
System.out.println("successfully saved");
factory.close();
session.close();
}
}
7) Run the application
Before running the application, determine that directory structure is like this.
Page 60
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
To run the hibernate application, right click on the StoreData class - Run As - Java Application.
1. Hibernate Logging
2. Example of Hibernate Logging
Logging enables the programmer to write the log details into a file permanently. Log4j and
Logback frameworks can be used in hibernate framework to support logging.
There are two ways to perform logging using log4j:
1. By log4j.xml file (or)
2. By log4j.properties file
Page 61
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Levels of Logging
Following are the common logging levels.
Levels Description
OFF This level is used to turn off logging.
WARNING This is a message level that indicates a problem.
SEVERE This is a message level that indicates a failure.
INFO This level is used for informational messages.
CONFIG This level is used for static configuration messages.
Page 62
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 63
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 64
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 65
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
There are three classes in this hierarchy. Employee is the super class for Regular_Employee
and Contract_Employee classes. Let's see the mapping file for this hierarchy.
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-5.3.dtd">
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp121" discriminator-
value="emp">
<id name="id">
<generator class="increment"></generator>
</id>
Page 66
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<property name="salary"></property>
<property name="bonus"></property>
</subclass>
</class>
</hibernate-mapping>
In case of table per class hierarchy an discriminator column is added by the hibernate
framework that specifies the type of the record. It is mainly used to distinguish the record. To
specify this, discriminator subelement of class must be specified.
The subclass subelement of class, specifies the subclass. In this case, Regular_Employee and
Contract_Employee are the subclasses of Employee class.
Page 67
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
package com.javatpoint.mypackage;
package com.javatpoint.mypackage;
package com.javatpoint.mypackage;
Page 68
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 69
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp121" discriminator-
value="emp">
<id name="id">
<generator class="increment"></generator>
</id>
Page 70
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
</class>
</hibernate-mapping>
3) Add mapping of hbm file in configuration file
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
<mapping resource="employee.hbm.xml"/>
Now the configuration file will look like this:
File: hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>
<mapping resource="employee.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
4) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.
Page 71
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
File: StoreData.java
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import
org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
Page 72
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 73
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
e3.setName("Arjun Kumar");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Output:
Page 74
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
There are three classes in this hierarchy. Employee is the super class for Regular_Employee
and Contract_Employee classes.
Page 75
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
File: Employee.java
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name = "employee101")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
@DiscriminatorValue(value="employee")
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
Page 76
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@DiscriminatorValue("regularemployee")
public class Regular_Employee extends Employee{
Page 77
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
package com.javatpoint.mypackage;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
@Entity
@DiscriminatorValue("contractemployee")
public class Contract_Employee extends Employee{
@Column(name="pay_per_hour")
@Column(name="contract_duration")
private String contract_duration;
Page 78
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
}
2) Add project information and configuration in pom.xml file.
Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>. ..</dependencies> tag.
Page 79
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.1.Final</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
3) Add the persistent classes in configuration file
Open the hibernate.cgf.xml file, and add entries of entity classes like this:
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
Page 80
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
4) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.
File: StoreTest.java
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import
org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
{
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hib
ernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Page 81
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Transaction t=session.beginTransaction();
Page 82
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Output:
Page 83
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp122">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<union-
subclass name="com.javatpoint.mypackage.Regular_Employee" table="regemp122">
<property name="salary"></property>
Page 84
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<property name="bonus"></property>
</union-subclass>
<union-
subclass name="com.javatpoint.mypackage.Contract_Employee" table="contemp122">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</union-subclass>
</class>
</hibernate-mapping>
In case of table per concrete class, there will be three tables in the database, each representing a particular cl
The union-subclass subelement of class, specifies the subclass. It adds the columns of parent table into this
other words, it is working as a union.
Page 85
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
File: Employee.java
package com.javatpoint.mypackage;
package com.javatpoint.mypackage;
Page 86
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
}
File: Contract_Employee.java
package com.javatpoint.mypackage;
Page 87
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp122">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<union-
subclass name="com.javatpoint.mypackage.Regular_Employee" table="regemp122">
<property name="salary"></property>
<property name="bonus"></property>
</union-subclass>
Page 88
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<union-
subclass name="com.javatpoint.mypackage.Contract_Employee" table="contemp122">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</union-subclass>
</class>
</hibernate-mapping>
3) Add mapping of hbm file in configuration file
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
<mapping resource="employee.hbm.xml"/>
Now the configuration file will look like this:
File: hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>
<mapping resource="employee.hbm.xml"/>
</session-factory>
Page 89
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
4) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import
org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
Page 90
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 91
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Table Per Concrete class using Annotation
In case of Table Per Concrete class, tables are created per class. So there are no nullable
values in the table. Disadvantage of this approach is that duplicate columns are created in the
subclass tables.
Here, we need to use @Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
annotation in the parent class and @AttributeOverrides annotation in the subclasses.
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS) specifies that we areusing
table per concrete class strategy. It should be specified in the parent class only.
@AttributeOverrides defines that parent class attributes will be overriden in this class. In
table structure, parent class table columns will be added in the subclass table.
The class hierarchy is given below:
Page 92
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 93
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
File: Employee.java
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name = "employee102")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
Page 95
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
File: Regular_Employee.java
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name="regularemployee102")
@AttributeOverrides({
@AttributeOverride(name="id", column=@Column(name="id")),
@AttributeOverride(name="name", column=@Column(name="name"))
})
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name="contractemployee102")
@AttributeOverrides({
@AttributeOverride(name="id", column=@Column(name="id")),
@AttributeOverride(name="name", column=@Column(name="name"))
Page 96
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
})
public class Contract_Employee extends Employee{
Page 97
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
private String contract_duration;
return pay_per_hour;
}
public void setPay_per_hour(float payPerHour) {
pay_per_hour = payPerHour;
}
public String getContract_duration() {
return contract_duration;
}
public void setContract_duration(String contractDuration) {
contract_duration = contractDuration;
}
}
2) Add project information and configuration in pom.xml file.
Open pom.xml file and click source. Now, add the below dependencies between
<dependencies>. ..</dependencies> tag.
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.1.Final</version>
</dependency>
Page 98
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<dependency>
<groupId>com.oracle</groupId>
Page 99
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
3) Add mapping of hbm file in configuration file
File: hibernate.cfg.xml
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
4) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
package com.javatpoint.mypackage;
Page 100
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import
org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
Page 102
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
e3.setName("Arjun Kumar");
e3.setPay_per_hour(1000);
e3.setContract_duration("15 hours");
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Table Per Subclass Example using xml file
In case of Table Per Subclass, subclass mapped tables are related to parent class mapped table
by primary key and foreign key relationship.
The <joined-subclass> element of class is used to map the child class with parent using the
primary key and foreign key relation.
In this example, we are going to use hb2ddl.auto property to generate the table automatically.
So we don't need to be worried about creating tables in the database.
Let's see the hierarchy of classes that we are going to map.
Page 103
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp123">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<joined-
subclass name="com.javatpoint.mypackage.Regular_Employee" table="regemp123">
<key column="eid"></key>
Page 104
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<property name="salary"></property>
<property name="bonus"></property>
</joined-subclass>
<joined-
subclass name="com.javatpoint.mypackage.Contract_Employee" table="contemp123">
<key column="eid"></key>
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</joined-subclass>
</class>
</hibernate-mapping>
In case of table per subclass class, there will be three tables in the database, each representing
a particular class.
The joined-subclass subelement of class, specifies the subclass.
The key sub-element of joined-subclass is used to generate the foreign key in the subclass
mapped table. This foreign key will be associated with the primary key of parent class
mapped table.
Table structure for Employee class
Page 105
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
package com.javatpoint.mypackage;
package com.javatpoint.mypackage;
Page 106
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
package com.javatpoint.mypackage;
Page 107
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
File: employee.hbm.xml
<hibernate-mapping>
<class name="com.javatpoint.mypackage.Employee" table="emp123">
<id name="id">
<generator class="increment"></generator>
</id>
<property name="name"></property>
<joined-
subclass name="com.javatpoint.mypackage.Regular_Employee" table="regemp123">
<key column="eid"></key>
<property name="salary"></property>
<property name="bonus"></property>
</joined-subclass>
Page 108
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<joined-
subclass name="com.javatpoint.mypackage.Contract_Employee" table="contemp123">
<key column="eid"></key>
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</joined-subclass>
</class>
</hibernate-mapping>
3) create configuration file
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
<mapping resource="employee.hbm.xml"/>
Now the configuration file will look like this:
File: hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="hbm2ddl.auto">update</property>
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</propert
y>
<mapping resource="employee.hbm.xml"/>
</session-factory>
Page 109
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
4) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import
org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
SessionFactory factory=meta.buildSessionFactory();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
Page 110
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 111
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Table Per Subclass using Annotation
As we have specified earlier, in case of table per subclass strategy, tables are created as per
persistent classes but they are treated using primary and foreign key. So there will not be any
duplicate column in the relation.
We need to specify @Inheritance(strategy=InheritanceType.JOINED) in the parent class
and @PrimaryKeyJoinColumn annotation in the subclasses.
Page 112
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 113
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
In this example we are creating the three classes and provide mapping of these classes in the
employee.hbm.xml file.
1) Create the Persistent classes
You need to create the persistent classes representing the inheritance. Let's create the three
classes for the above hierarchy:
File: Employee.java
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name = "employee103")
@Inheritance(strategy=InheritanceType.JOINED)
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name = "id")
private int id;
@Column(name = "name")
private String name;
package com.javatpoint.mypackage;
import javax.persistence.*;
Page 114
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@Entity
Page 115
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
@Table(name="regularemployee103")
@PrimaryKeyJoinColumn(name="ID")
public class Regular_Employee extends Employee{
@Column(name="salary")
private float salary;
@Column(name="bonus")
private int bonus;
package com.javatpoint.mypackage;
import javax.persistence.*;
@Entity
@Table(name="contractemployee103")
@PrimaryKeyJoinColumn(name="ID")
public class Contract_Employee extends Employee{
@Column(name="pay_per_hour")
private float pay_per_hour;
@Column(name="contract_duration")
Page 116
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 117
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.4.0</version>
</dependency>
3) Create the configuration file
Open the hibernate.cgf.xml file, and add an entry of mapping resource like this:
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
Now the configuration file will look like this:
File: hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-5.3.dtd">
<session-factory>
<property name="hbm2ddl.auto">update</property>
Page 118
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<property name="dialect">org.hibernate.dialect.Oracle9Dialect</property>
<property name="connection.url">jdbc:oracle:thin:@localhost:1521:xe</property>
<property name="connection.username">system</property>
<property name="connection.password">jtp</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<mapping class="com.javatpoint.mypackage.Employee"/>
<mapping class="com.javatpoint.mypackage.Contract_Employee"/>
<mapping class="com.javatpoint.mypackage.Regular_Employee"/>
</session-factory>
</hibernate-configuration>
The hbm2ddl.auto property is defined for creating automatic table in the database.
3) Create the class that stores the persistent object
In this class, we are simply storing the employee objects in the database.
File: StoreData.java
package com.javatpoint.mypackage;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import
org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
Page 119
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 120
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();
Transaction t=session.beginTransaction();
session.persist(e1);
session.persist(e2);
session.persist(e3);
t.commit();
session.close();
System.out.println("success");
}
}
Page 121
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
t.commit();//transaction is commited
session.close();
Solution by using HibernateTemplate class of Spring Framework:
You can simply write this:
Page 122
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
7) Object load(Class entityClass, returns the persistent object on the basis of given
Serializable id) id.
Steps
Let's see what are the simple steps for hibernate and spring integration:
1. create table in the database It is optional.
2. create applicationContext.xml file It contains information of DataSource,
SessionFactory etc.
3. create Employee.java file It is the persistent class
4. create employee.hbm.xml file It is the mapping file.
5. create EmployeeDao.java file It is the dao class that uses HibernateTemplate.
6. create InsertTest.java file It calls methods of EmployeeDao class.
Example of Hibernate and spring integration
In this example, we are going to integrate the hibernate application with spring. Let's see
the directory structure of spring and hibernate example.
Page 123
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 124
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 125
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
3) employee.hbm.xml
This mapping file contains all the information of the persistent class.
<?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>
<class name="com.javatpoint.Employee" table="emp558">
<id name="id">
<generator class="assigned"></generator>
</id>
<property name="name"></property>
<property name="salary"></property>
</class>
</hibernate-mapping>
4) EmployeeDao.java
It is a java class that uses the HibernateTemplate class method to persist the object of
Employee class.
package com.javatpoint;
import org.springframework.orm.hibernate3.HibernateTemplate;
import java.util.*;
HibernateTemplate
template;
this.template = template;
}
Page 126
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Page 127
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
template.save(e);
}
//method to update employee
public void updateEmployee(Employee e){
template.update(e);
}
//method to delete employee
public void deleteEmployee(Employee e){
template.delete(e);
}
//method to return one employee of given id
public Employee getById(int id){
Employee e=(Employee)template.get(Employee.class,id);
return e;
}
//method to return all employees
public List<Employee> getEmployees(){
List<Employee> list=new ArrayList<Employee>();
list=template.loadAll(Employee.class);
return list;
}
}
5) applicationContext.xml
In this file, we are providing all the informations of the database in
the BasicDataSource object. This object is used in the LocalSessionFactoryBean class
object, containing some other informations such as mappingResources and
hibernateProperties. The object of LocalSessionFactoryBean class is used in the
HibernateTemplate class. Let's see the code of applicationContext.xml file.
Page 128
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
File: applicationContext.xml
Page 129
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
<property name="mappingResources">
<list>
<value>employee.hbm.xml</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
Page 130
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
</beans>
6) InsertTest.java
This class uses the EmployeeDao class object and calls its saveEmployee method by passing
the object of Employee class.
package com.javatpoint;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
EmployeeDao dao=(EmployeeDao)factory.getBean("d");
dao.saveEmployee(e);
}
}
Page 131
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
Now, if you see the table in the oracle database, record is inserted successfully.
Page 132
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V
</props>
If you write this code, you don't need to create table because table
will be createdautomatically.
Page 133