0% found this document useful (0 votes)
2 views

Cb3303 Notes Unit 5

Unit V of the course on Web Development Frameworks focuses on the Java Development Environment, specifically Spring Boot and Hibernate. It covers the setup and architecture of Spring Boot, including creating projects using various IDEs, Spring Boot CLI, and the use of Spring annotations. The unit emphasizes the advantages of Spring Boot over traditional Spring frameworks, particularly in terms of rapid application development and simplified configuration.

Uploaded by

sriramlord50
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Cb3303 Notes Unit 5

Unit V of the course on Web Development Frameworks focuses on the Java Development Environment, specifically Spring Boot and Hibernate. It covers the setup and architecture of Spring Boot, including creating projects using various IDEs, Spring Boot CLI, and the use of Spring annotations. The unit emphasizes the advantages of Spring Boot over traditional Spring frameworks, particularly in terms of rapid application development and simplified configuration.

Uploaded by

sriramlord50
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 133

Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

UNIT V – JAVA DEVELOPMENT ENVIRONMENT


Introduction to Spring Boot – Creating Project – Spring Initializer – Download and Install STS IDE – Spring Boot
Example – Spring Boot CLI - Spring Boot Annotations - Spring Boot Application Properties - Spring Boot Starter
Web - Spring Boot AOP Hibernate – Hibernate Architecture - Hibernate with eclipse – Hibernate web application
example – Hibernate Log4j – Hibernate Inheritance Mapping – Hibernate and Spring Integration.

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

Step 3: Import Spring Boot Project in Eclipse IDE


Go to the Eclipse IDE for Enterprise Java and Web Developer > File > Import as shownin
the below image.

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

Create a Spring Boot Project in STS IDE


Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise
applications. It is easier, faster, and more convenient. And most importantly it is based on
Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next
generation of Spring tooling for the favourite coding environment. Largely rebuilt from
scratch, it provides world-class support for developing Spring-based enterprise applications,
whether you prefer Eclipse, Visual Studio Code, or Theia IDE.
Procedure:
1. Install Spring Tool Suite IDE
2. Create a new Spring project
3. Fill details in the pop-up window and press Next.
4. Choose Spring Boot version and select dependencies and press Next.
5. Click on the ‘Finish’ button.
Step 1: Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE
For this user must have pre-requisite knowledge of downloading and installing Spring Tool
Suite IDE
Step 2: Go to the File > New > Spring Starter Project as shown in the below image as
follows:

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

Name: Your Project Name

Type: Maven Project

Java Version: 11 or greater than 11

Packaging: As your need Language:

As your need

Group: A unique base name of the company or group that created the project
Artifact: A unique name of the project

Version: Default Description:

As your need Package: Your

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

Step 5: Now simply click on the Finish button.

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

Create a Spring Boot Project in IntelliJ IDEA


IntelliJ is an integrated development environment (IDE) written in Java. It is used for
developing computer software. This IDE is developed by Jetbrains and is available as an
Apache 2 Licensed community edition and a commercial edition.
Procedure:
1. Install IntelliJ IDEA on the local machine.
2. Create a Spring Boot Project in Spring Initializr
3. Import Spring Boot Project in IntelliJ IDEA
4. Choose the project that you have created in above step 2.
Step 1: Install IntelliJ IDEA on the local machine for that do go through pre-requisite for
installing Intellij Idea on the system.
Step 2: Create a Spring Boot Project in Spring Initializr
Create a Spring Boot project and do 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 and do go through the introduction to Spring
Initializr before proceeding further.

Page 11
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Step 3: Import Spring Boot Project in IntelliJ IDEA


After successfully installing IntelliJ IDEA go to the File > Open as seen in the below image.

Page 12
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

After this, a pop-up window will occur like the following.


Step 4: Here you have to choose the project that you have created in step 2. For example,
here we have created the spring boot project named “demo” and stored it inside the
Downloads folder and you can see we can find the same inside the Downloads folder. At last
click on the OK button. And we are done creating the Spring Boot project in IntelliJ IDEA.
Please wait for some time to download all the required files.

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

Spring Boot CLI


It is a tool which you can download from the official site of Spring Framework. Here, we are
explaining steps.
Download the CLI tool from official site as we are doing here.

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

Create a groovy file.

Create a controller in the groovy file.

Execute this file


By using the following command.
1. ./spring run SpringBootCliExample.groovy
After executing the above command, it starts the execution and produces the following
output.
And after lots of lines. It shows the current status of application as follow.

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

5. Spring Data Annotations


6. Spring Bean Annotations
Type 1: Spring Core Annotations
Spring annotations present in
the org.springframework.beans.factory.annotation and
org.springframework.context.annotation packages are commonly known as Spring Core
annotations. We can divide them into two categories:

 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;

1.3 : Constructor injection


 Java

class Student {
Address address;

@Autowired
Student(Address address) {
this.address = address;
}
}

1.4 : Setter injection


 Java

class Student {
Address address;

@Autowired
void setaddress(Address address) {
this.address = address;
}

B Context Configuration Annotations


@Profile: If you want Spring to use a @Component class or a @Bean method only when a
specific profile is active then you can mark it with @Profile.
@Component
@Profile("developer")
public class Employee {}

Page 19
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Type 2: Spring Web Annotations

Spring annotations present in the org.springframework.web.bind.annotation packages


are commonly known as Spring Web annotations. Some of the annotations that are
available inthis category are:

 @RequestMapping
 @RequestBody
 @PathVariable
 @RequestParam
 Response Handling Annotations
 @ResponseBody
 @ExceptionHandler
 @ResponseStatus
 @Controller
 @RestController
 @ModelAttribute
 @CrossOrigin
Example: @Controller

Spring @Controller annotation is also a specialization of @Component annotation. The


@Controller annotation indicates that a particular class serves the role of a controller. Spring
Controller annotation is typically used in combination with annotated handler methods based
on the @RequestMapping annotation. It can be applied to classes only. It’s used to mark a
class as a web request handler. It’s mostly used with Spring MVC applications. This
annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher
scans such annotated classes for mapped methods and detects @RequestMapping
annotations.
 Java

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 {

// Main driver method


public static void main(String[] args)

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

This annotation is used to enable asynchronous functionality in Spring.


@Configuration
@EnableAsync
class Config {}
Type 5: Spring Data Annotations

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

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
 @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 {

// Main driver method


public static void main(String[] args)

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 {

public static void main(String[] args) {

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 {

public static void main(String[] args) {

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 {

// Main driver method


public static void main(String[] args)

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 {

// Insert code here


}

6. @ConditionalOnBean Annotation and @ConditionalOnMissingBean Annotation


These annotations are used to let a bean be included based on the presence or absence of
specific beans.
Example:
 Java

@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.

SpEL (Spring Expression Language): It is a powerful expression language that supports


querying and manipulating an object graph at runtime.

Example:
 Java

@Bean
@ConditionalOnExpression("${env} && ${havingValue == 'local'}")

DataSource dataSource()
{
// Insert code here

10. @ConditionalOnCloudPlatform Annotation


These annotations are used to let configuration be included when the specified cloud platform
is active.
Example:
 Java

@Configuration
@ConditionalOnCloudPlatform(CloudPlatform.CLOUD_FOUNDRY)

public class CloudConfigurationExample

{
// Insert code here

Spring Boot Starter Web


There are two important features of spring-boot-starter-web:
o It is compatible for web development
o Auto configuration

Page 31
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

If we want to develop a web application, we need to add the following dependency in


pom.xml file:
1. <dependency>
2. <groupId>org.springframework.boot</groupId>
3. <artifactId>spring-boot-starter-web</artifactId>
4. <version>2.2.2.RELEASE</version>
5. </dependency>
Starter of Spring web uses Spring MVC, REST and Tomcat as a default embedded server.
The single spring-boot-starter-web dependency transitively pulls in all dependencies related
to web development. It also reduces the build dependency count. The spring-boot-starter-web
transitively depends on the following:
o org.springframework.boot:spring-boot-starter
o org.springframework.boot:spring-boot-starter-tomcat
o org.springframework.boot:spring-boot-starter-validation
o com.fasterxml.jackson.core:jackson-databind
o org.springframework:spring-web
o org.springframework:spring-webmvc
By default, the spring-boot-starter-web contains the following tomcat server dependency:
1. <dependency>
2. <groupId>org.springframework.boot</groupId>
3. <artifactId>spring-boot-starter-tomcat</artifactId>
4. <version>2.0.0.RELEASE</version>
5. <scope>compile</scope>
6. </dependency>
The spring-boot-starter-web auto-configures the following things that are required for the
web development:
o Dispatcher Servlet
o Error Page
o Web JARs for managing the static dependencies
o Embedded servlet container

Page 32
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Spring Boot Embedded Web Server


Each Spring Boot application includes an embedded server. Embedded server is embedded as
a part of deployable application. The advantage of embedded server is, we do not require pre-
installed server in the environment. With Spring Boot, default embedded server is Tomcat.
Spring Boot also supports another two embedded servers:
o Jetty Server
o Undertow Server
Using another embedded web server
For servlet stack applications, the spring-boot-starter-web includes Tomcat by

including spring-boot-starter-tomcat, but we can use spring-boot-starter-jetty or spring-


boot-starter-undertow instead.

For reactive stack applications, the spring-boot-starter-webflux includes Reactor Netty by


including spring-boot-starter-reactor-netty, but we can use spring-boot-starter-tomcat,
spring-boot-starter-jetty, or spring-boot-starter-undertow instead.

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

We can also customize the behavior of the Undertow server by using


the application.properties file.

spring-boot-starter-web vs. spring-boot-starter-tomcat


The spring-boot-starter-web contains the spring web dependencies that includes spring-boot-
starter-tomcat. The spring-boot-starter-web contains the following:
o spring-boot-starter
o jackson
o spring-core
o spring-mvc
o spring-boot-starter-tomcat
While the spring-boot-starter-tomcat contains everything related to Tomcat server.

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

called cross-cutting concerns.

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.

Advice: It is an implementation of cross- Method bodies: It is an implementation of


cutting concerns. the business logic concerns.

Waver: It constructs code (source or Compiler: It converts source code to


object) with advice. object code.

Page 40
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Spring AOP vs. AspectJ


The differences between AOP and OOP are as follows:
Spring AOP AspectJ
There is a need for a separate It requires the AspectJ compiler.
compilation process.
It supports only method execution It supports all pointcuts.
pointcuts.
It can be implemented on beans managed It can be implemented on all domain objects.
by Spring Container.
It supports only method level weaving. It can wave fields, methods, constructors, static
initializers, final class, etc.
Types of AOP Advices
There are five types of AOP advices are as follows:
o Before Advice
o After Advice
o Around Advice
o After Throwing
o After Returning
Before Advice: An advice that executes before a join point, is called before advice. We
use @Before annotation to mark an advice as Before advice.
After Advice: An advice that executes after a join point, is called after advice. We
use @After annotation to mark an advice as After advice.
Around Advice: An advice that executes before and after of a join point, is called around
advice.

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

Let's create the simple Persistent class:


Employee.java
package com.javatpoint.mypackage;

public class Employee {

private int id;


private String firstName,lastName;

public int getId() {

return id;

}
public void setId(int id) {

this.id = id;

}
public String getFirstName() {

return firstName;

}
public void setFirstName(String firstName) {

this.firstName = firstName;
}
public String getLastName() {

return lastName;

}
public void setLastName(String lastName) {

this.lastName = lastName;
}

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

2) Create the mapping file for Persistent class


The mapping file name conventionally, should be class_name.hbm.xml. There are many
elements of the mapping file.
o hibernate-mapping : It is the root element in the mapping file that contains all the
mapping elements.
o class : It is the sub-element of the hibernate-mapping element. It specifies the
Persistent class.
o id : It is the sub element of class. It specifies the primary key attribute in the class.
o generator : It is the sub-element of id. It is used to generate the primary key. There
are many generator classes such as assigned, increment, hilo, sequence, native etc. We
will learn all the generator classes later.
o property : It is the sub-element of class that specifies the property name of the
Persistent class.
Let's see the mapping file for the Employee class:
employee.hbm.xml
<?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="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

3) Create the Configuration file


The configuration file contains information about the database and mapping file.
Conventionally, its name should be 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>
<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;

public class StoreData {

public static void main(String[] args) {

//Create typesafe ServiceRegistry object


StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hiber
nate.cfg.xml").build();

Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory = meta.getSessionFactoryBuilder().build();


Session session = factory.openSession();
Transaction t = session.beginTransaction();

Employee e1=new Employee();


e1.setId(101);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");

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

5) Load the jar file


For successfully running the hibernate application, you should have the hibernate5.jar file.
Download the required jar files for hibernate
6) How to run the first hibernate application without IDE
We may run this hibernate application by IDE (e.g. Eclipse, Myeclipse, Netbeans etc.) or
without IDE. We will learn about creating hibernate application in Eclipse IDE in next
chapter.
To run the hibernate application without IDE:
o Install the oracle10g for this example.
o Load the jar files for hibernate. (One of the way to load the jar file is copy all the jar
files under the JRE/lib/ext folder). It is better to put these jar files inside the public
and private JRE both.
o Now, run the StoreData class by java com.javatpoint.mypackage.StoreData

Hibernate Example using XML in Eclipse


For creating the first hibernate application in Eclipse IDE, we need to follow the following
steps:
1. Create the java project
2. Add jar files for hibernate
3. Create the Persistent class

Page 53
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

4. Create the mapping file for Persistent class


5. Create the Configuration file
6. Create the class that retrieves or stores the persistent object
7. Run the application
1) Create the java project

Create the java project by File Menu - New - project - java project . Now specify the
project name e.g. firsthb then next - finish .

2) Add jar files for hibernate

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.

Download the required jar file

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;

public class Employee {

private int id;


private String firstName,lastName;

public int getId() {

return id;

}
public void setId(int id) {

this.id = id;

}
public String getFirstName() {

return firstName;

}
public void setFirstName(String firstName) {

this.firstName = firstName;
}
public String getLastName() {

return lastName;

}
public void setLastName(String lastName) {

this.lastName = lastName;
}
}
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

- ok. It must be outside the package.


employee.hbm.xml

Page 56
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

<?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="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;

public class StoreData {

public static void main( String[] args )

{
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hi
bernate.cfg.xml").build();

Page 58
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();

Page 59
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

SessionFactory factory = meta.getSessionFactoryBuilder().build();


Session session = factory.openSession();
Transaction t = session.beginTransaction();

Employee e1=new Employee();


e1.setId(1);
e1.setFirstName("Gaurav");
e1.setLastName("Chawla");

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.

Hibernate Logging by Log4j using xml file

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.

Steps to perform Hibernate Logging by Log4j using xml file


There are two ways to perform logging using log4j using xml file:
1. Load the log4j jar files with hibernate
2. Create the log4j.xml file inside the src folder (parallel with hibernate.cfg.xml file)
Example of Hibernate Logging by Log4j using xml file
This is the first example of hibernate application with logging support using log4j.
Load the required jar files
download all the required jar files
Create log4j.xml file
Now you need to create log4j.xml file. In this example, all the log details will be written in
the C:/javatpointlog.log file.
log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
debug="false">
<appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{
2}: %m%n" />
</layout>
</appender>

Page 62
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

<appender name="ASYNC" class="org.apache.log4j.AsyncAppender">


<appender-ref ref="CONSOLE" />
<appender-ref ref="FILE" />
</appender>
<appender name="FILE" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="C:/javatpointlog.log" />
<param name="MaxBackupIndex" value="100" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{dd/MM/yy hh:mm:ss:sss z}] %5p %c{
2}: %m%n" />
</layout>
</appender>
<category name="org.hibernate">
<priority value="DEBUG" />
</category>
<category name="java.sql">
<priority value="debug" />
</category>
<root>
<priority value="INFO" />
<appender-ref ref="FILE" />
</root>
</log4j:configuration>
Hibernate Logging by Log4j using properties file
1. Hibernate Logging
2. Example of Hibernate Logging
As we know, Log4j and Logback frameworks are used to support logging in hibernate, there
are two ways to perform logging using log4j:
1. By log4j.xml file (or)
2. By log4j.properties file
Here, we are going to enable logging using log4j through properties file.

Page 63
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Steps to perform Hibernate Logging by Log4j using properties file


There are two ways to perform logging using log4j using properties file:
1. Load the log4j jar files with hibernate
2. Create the log4j.properties file inside the src folder (parallel with hibernate.cfg.xml
file)
Example of Hibernate Logging by Log4j using properties file
You can enable logging in hibernate by following only two steps in any hibernate example.
This is the first example of hibernate application with logging support using log4j.
Load the required jar files
You need to load the slf4j.jar and log4j.jar files with hibernate jar files.
download all the required jar files
Create log4j.properties file
Now you need to create log4j.properties file. In this example, all the log details will be
written in the C:\\javatpointhibernate.log file.
log4j.properties
# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\javatpointhibernate.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m
%n

# Direct log messages to stdout


log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %
m%n

# Root logger option

Page 64
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

log4j.rootLogger=INFO, file, stdout

# Log everything. Good for troubleshooting


log4j.logger.org.hibernate=INFO

# Log all JDBC parameters


log4j.logger.org.hibernate.type=ALL
Hibernate Inheritance Mapping Tutorial
We can map the inheritance hierarchy classes with the table of the database. There are three
inheritance mapping strategies defined in the hibernate:
1. Table Per Hierarchy
2. Table Per Concrete class
3. Table Per Subclass
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 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 Subclass
In this strategy, tables are created as per class but related by foreign key. So there are no
duplicate columns.
Hibernate Table Per Hierarchy using xml file
By this inheritance strategy, we can map the whole hierarchy by single table only. Here, an
extra column (also known as discriminator column) is created in the table to identify the
class.
Let's understand the problem first. I want to map the whole hierarchy given below into one
table of the database.

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>

<discriminator column="type" type="string"></discriminator>


<property name="name"></property>

<subclass name="com.javatpoint.mypackage.Regular_Employee" discriminator-


value="reg_emp">

Page 66
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

<property name="salary"></property>
<property name="bonus"></property>
</subclass>

<subclass name="com.javatpoint.mypackage.Contract_Employee" discriminator-


value="con_emp">
<property name="pay_per_hour"></property>
<property name="contract_duration"></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.

The table structure for this hierarchy is as shown below:

Page 67
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Example of Table per class hierarchy


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;

public class Employee {

private int id;


private String name;

//getters and setters


}
File: Regular_Employee.java

package com.javatpoint.mypackage;

public class Regular_Employee extends Employee{

private float salary;

private int bonus;

//getters and setters


}
File: Contract_Employee.java

package com.javatpoint.mypackage;

public class Contract_Employee extends Employee{

Page 68
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

private float pay_per_hour;

private String contract_duration;

Page 69
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

//getters and setters


}
2) Create the mapping file for Persistent class
The mapping has been discussed above for the hierarchy.
File: employee.hbm.xml

<?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>

<discriminator column="type" type="string"></discriminator>


<property name="name"></property>

<subclass name="com.javatpoint.mypackage.Regular_Employee" discriminator-


value="reg_emp">
<property name="salary"></property>
<property name="bonus"></property>
</subclass>

<subclass name="com.javatpoint.mypackage.Contract_Employee" discriminator-


value="con_emp">
<property name="pay_per_hour"></property>
<property name="contract_duration"></property>
</subclass>

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

<?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>
<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;

public class StoreData {

public static void main(String[] args) {

StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibern


ate.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();

Transaction t=session.beginTransaction();

Employee e1=new Employee();


e1.setName("Gaurav Chawla");

Regular_Employee e2=new Regular_Employee();


e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);

Page 72
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Contract_Employee e3=new Contract_Employee();

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:

Hibernate Table Per Hierarchy using Annotation


You need to use @Inheritance(strategy=InheritanceType.SINGLE_TABLE),
@DiscriminatorColumn and @DiscriminatorValue annotations for mapping table per
hierarchy strategy.
In case of table per hierarchy, only one table is required to map the inheritance hierarchy.
Here, an extra column (also known as discriminator column) is created in the table to
identify the class.
Let's see the inheritance hierarchy:

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.

Example of Hibernate Table Per Hierarchy using Annotation


You need to follow the following steps to create simple example:
o Create the persistent classes
o Edit pom.xml file
o Create the configuration file
o Create the class to store the fetch the data
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:

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")

public class Employee {

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name = "id")
private int id;

@Column(name = "name")
private String name;

//setters and getters


}
File: Regular_Employee.java

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;

//setters and getters


}
File: Contract_Employee.java

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")

private float pay_per_hour;

@Column(name="contract_duration")
private String contract_duration;

//setters and getters

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:

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


<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 5.3//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-5.3.dtd">
<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 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;

public class StoreTest {

public static void main(String args[])

{
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

Employee e1=new Employee();


e1.setName("Gaurav Chawla");

Regular_Employee e2=new Regular_Employee();


e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


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:

Table Per Concrete class using xml file


In case of Table Per Concrete class, there will be three tables in the database having no
relations to each other. There are two ways to map the table with table per concrete class
strategy.
o By union-subclass element

Page 83
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

o By self creating the table for each class


Let's understand what hierarchy we are going to map.

Let's see how can we map this hierarchy by union-subclass element:


<?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="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.

Table structure for Employee class

Table structure for Regular_Employee class

Table structure for Contract_Employee class

Page 85
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Example of Table per concrete class


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;

public class Employee {

private int id;


private String name;

//getters and setters


}
File: Regular_Employee.java

package com.javatpoint.mypackage;

public class Regular_Employee extends Employee{

private float salary;

private int bonus;

//getters and setters

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

public class Contract_Employee extends Employee{

private float pay_per_hour;

private String contract_duration;

//getters and setters


}
2) Create the mapping file for Persistent class
The mapping has been discussed above for the hierarchy.
File: employee.hbm.xml

<?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="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

<?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>
<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;

public class StoreData {

public static void main(String[] args) {

StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibern


ate.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();

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

Employee e1=new Employee();


e1.setName("Gaurav Chawla");

Page 91
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Regular_Employee e2=new Regular_Employee();


e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


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 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

Table structure for Employee class

Table structure for Regular_Employee class

Table structure for Contract_Employee class

Page 93
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Example of Table per concrete class


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 = "employee102")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)

public class Employee {

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name = "id")
private int id;

@Column(name = "name")

private String name;

//setters and getters


Page 94
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

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;

//setters and getters


}
File: Contract_Employee.java

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;

public float getPay_per_hour() {

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

<?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">

<!-- Generated by MyEclipse Hibernate Tools. -->


<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</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.
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;

public class StoreData {

public static void main(String[] args) {

StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibe


rnate.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();

SessionFactory factory=meta.getSessionFactoryBuilder().build();
Session session=factory.openSession();

Transaction t=session.beginTransaction();

Employee e1=new Employee();


e1.setName("Gaurav Chawla");

Regular_Employee e2=new Regular_Employee();


e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);
Page 101
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Contract_Employee e3=new Contract_Employee();

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

Let's see how can we map this hierarchy by joined-subclass element:


<?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="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

Table structure for Regular_Employee class

Page 105
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Table structure for Contract_Employee class

Example of Table per subclass class


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;

public class Employee {

private int id;


private String name;

//getters and setters


}
File: Regular_Employee.java

package com.javatpoint.mypackage;

public class Regular_Employee extends Employee{

private float salary;

private int bonus;

//getters and setters


}
File: Contract_Employee.java

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

public class Contract_Employee extends Employee{

private float pay_per_hour;

private String contract_duration;

//getters and setters


}
2) Create the mapping file for Persistent class
The mapping has been discussed above for the hierarchy.

File: employee.hbm.xml

<?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="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

<?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>
<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;

public class StoreData {

public static void main(String[] args) {

StandardServiceRegistry ssr=new StandardServiceRegistryBuilder().configure("hibernate


.cfg.xml").build();
Metadata meta=new MetadataSources(ssr).getMetadataBuilder().build();

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

Employee e1=new Employee();


e1.setName("Gaurav Chawla");

Page 111
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Regular_Employee e2=new Regular_Employee();


e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


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 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.

Let's see the hierarchy of classes that we are going to map.

Page 112
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

The table structure for each table will be as follows:


Table structure for Employee class

Table structure for Regular_Employee class

Table structure for Contract_Employee class

Example of Table per subclass class using Annotation

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)

public class Employee {

@Id

@GeneratedValue(strategy=GenerationType.AUTO)

@Column(name = "id")
private int id;

@Column(name = "name")
private String name;

//setters and getters


}
File: Regular_Employee.java

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;

//setters and getters


}
File: Contract_Employee.java

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")

private String contract_duration;

Page 116
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

//setters and getters


}

Page 117
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.
<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) 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">

<!-- Generated by MyEclipse Hibernate Tools. -->


<hibernate-configuration>

<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;

public class StoreData {

Page 119
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

public static void main(String args[])

Page 120
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

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();

Transaction t=session.beginTransaction();

Employee e1=new Employee();


e1.setName("Gaurav Chawla");

Regular_Employee e2=new Regular_Employee();


e2.setName("Vivek Kumar");
e2.setSalary(50000);
e2.setBonus(5);

Contract_Employee e3=new Contract_Employee();


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");
}
}

Page 121
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

Hibernate and Spring Integration


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.
Understanding problem without using spring:
Let's understand it by the code of hibernate given below:
//creating configuration
Configuration cfg=new Configuration();
cfg.configure("hibernate.cfg.xml");

//creating seession factory object


SessionFactory factory=cfg.buildSessionFactory();

//creating session object


Session session=factory.openSession();

//creating transaction object


Transaction t=session.beginTransaction();

Employee e1=new Employee(111,"arun",40000);


session.persist(e1);//persisting the object

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

1. Employee e1=new Employee(111,"arun",40000);


2. hibernateTemplate.save(e1);
Methods of HibernateTemplate class
Let's see a list of commonly used methods of HibernateTemplate class.
No. Method Description

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


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

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


5) void delete(Object entity) deletes the given object on the basis of id.
6) Object get(Class entityClass, returns the persistent object on the basis of given
Serializable id) id.

7) Object load(Class entityClass, returns the persistent object on the basis of given
Serializable id) id.

8) List loadAll(Class entityClass) returns the all the persistent objects.

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

1) create the table in the database


In this example, we are using the Oracle as the database, but you may use any database. Let's
create the table in the oracle database
CREATE TABLE "EMP558"
( "ID" NUMBER(10,0) NOT NULL ENABLE,
"NAME" VARCHAR2(255 CHAR),
"SALARY" FLOAT(126),
PRIMARY KEY ("ID") ENABLE
)
/
2) Employee.java
It is a simple POJO class. Here it works as the persistent class for hibernate.
package com.javatpoint;

public class Employee {

private int id;

private String name;

private float salary;

//getters and setters

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.*;

public class EmployeeDao {

HibernateTemplate

template;

public void setTemplate(HibernateTemplate template) {

this.template = template;
}

Page 126
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

//method to save employee


public void saveEmployee(Employee e){

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

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


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

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">


<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></pro
perty>
<property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property>
<property name="username" value="system"></property>

Page 129
Course Code/Title: AM3303 WEB DEVELOPMENT FRAMEWORKS AND PRACTICES UNIT: V

<property name="password" value="oracle"></property>


</bean>

<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.LocalSessi


onFactoryBean">
<property name="dataSource" ref="dataSource"></property>

<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>

<bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate"


>
<property name="sessionFactory" ref="mysessionFactory"></property>
</bean>

<bean id="d" class="com.javatpoint.EmployeeDao">


<property name="template" ref="template"></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;

public class InsertTest {

public static void main(String[] args) {

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


BeanFactory factory=new XmlBeanFactory(r);

EmployeeDao dao=(EmployeeDao)factory.getBean("d");

Employee e=new Employee();


e.setId(114);
e.setName("varun");
e.setSalary(50000);

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

Enabling automatic table creation, showing sql queries etc.


You can enable many hibernate properties like automatic table creation by
hbm2ddl.auto etc.in applicationContext.xml file. Let's see the code:
<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>
If you write this code, you don't need to create table because table
will be createdautomatically.

Page 133

You might also like