SlideShare a Scribd company logo
1 of 65
Spring + Hibernate
Presenter : Majurageerthan Arumugathasan
Contents
1. Spring
2. Hibernate
3. Sample Project
What is Spring ?
Spring Framework
Wait…? What is a Framework ?
A framework is a reusable, “semi-complete” application that
can be specialized to produce custom applications [Johnson
and Foote, 1988].
Pros And Cons Of Using Web Frameworks!
Positive Negative
Efficiency Lack of option to modify core
behavior
Security Limitation
Cost You learn the framework, not
the language
Support
source: https://www.vizteams.com/blog/advantages-and-disadvantages-of-frameworks/
Fun Fact
Spring Framework Overview
● The term "Spring" means different things in different contexts.
● The Spring Framework is a lightweight solution and a potential one-stop-
shop for building your enterprise-ready applications.
● Initial release : 1 October 2002; 16 years ago
● Spring Framework 5.1
○ requires JDK 8 or higher
○ Java EE 7 level (e.g. Servlet 3.1+, JPA 2.1+) as a minimum
Source : https://docs.spring.io/spring/docs/current/spring-framework-
reference/overview.html
Features
● Core technologies: dependency injection, events, resources, i18n, validation, data
binding, type conversion, SpEL, AOP.
● Testing: mock objects, TestContext framework, Spring MVC Test, WebTestClient.
● Data Access: transactions, DAO support, JDBC, ORM, Marshalling XML.
● Spring MVC and Spring WebFlux web frameworks.
● Integration: remoting, JMS, JCA, JMX, email, tasks, scheduling, cache.
● Languages: Kotlin, Groovy, dynamic languages.
Source : https://spring.io/projects/spring-framework#overview
Introduction to the Spring Framework
The Spring Framework
consists of features
organized into about 20
modules.
Core Technologies
Configuration metadata represents how you as an application developer tell the
Spring container to instantiate, configure, and assemble the objects in your
application.
Configuration metadata is traditionally supplied in a simple and intuitive XML
format.
XML-based configuration
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="accountDao"
class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao">
<!-- additional collaborators and configuration for this bean go here -->
</bean>
<!-- more bean definitions for data access objects go here -->
XML-based metadata is not the only allowed form
of configuration metadata
Annotation-based configuration: Spring 2.5 introduced support for
annotation-based configuration metadata.
Java-based configuration: Starting with Spring 3.0, many features provided by
the Spring JavaConfig project became part of the core Spring Framework
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-
beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-
4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-
context-4.0.xsd">
<context:component-scan base-package="hms.controller" />
<context:component-scan base-package="dao" />
<context:component-scan base-package="hms.service" />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix">
<value>/WEB-INF/pages/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
</beans>
XML-based configuration
package hms.config.spring.mvc;
@Configuration
@EnableWebMvc
@ComponentScans({
@ComponentScan("hms.controller"),
@ComponentScan("dao"),
@ComponentScan("hms.service")
})
public class WebMVCConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
Java-based configuration
Spring Java Configuration Advantages
1. Easy to understand
2. Java is type safe. Compiler will report issues if you are configuring right bean
class qualifiers.
3. XML based on configuration can quickly grow big.
4. Search is much simpler, refactoring will be easier. Finding a bean definition
will be far easier.
5. etc,etc…….
Java-based Config
Wait….
Spring Web MVC
dependencies {
provided("javax.servlet:javax.servlet-api:4.0.1")
compile(project(":spring-aop"))
compile(project(":spring-beans"))
compile(project(":spring-context"))
compile(project(":spring-core"))
compile(project(":spring-expression"))
compile(project(":spring-web"))
}
Source : https://github.com/spring-projects/spring-framework/blob/master/spring-webmvc/spring-webmvc.gradle
mvn dependency:tree
[INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ hms-orm ---
[INFO] com.maju:hms-orm:jar:1.0-SNAPSHOT
[INFO] +- org.springframework:spring-webmvc:jar:5.1.0.RELEASE:compile
[INFO] | +- org.springframework:spring-aop:jar:5.1.0.RELEASE:compile
[INFO] | +- org.springframework:spring-beans:jar:5.1.0.RELEASE:compile
[INFO] | +- org.springframework:spring-context:jar:5.1.0.RELEASE:compile
[INFO] | +- org.springframework:spring-core:jar:5.1.0.RELEASE:compile
[INFO] | | - org.springframework:spring-jcl:jar:5.1.0.RELEASE:compile
[INFO] | +- org.springframework:spring-expression:jar:5.1.0.RELEASE:compile
[INFO] | - org.springframework:spring-web:jar:5.1.0.RELEASE:compile
[INFO] +- org.springframework:spring-orm:jar:5.1.0.RELEASE:compile
[INFO] | +- org.springframework:spring-jdbc:jar:5.1.0.RELEASE:compile
[INFO] | - org.springframework:spring-tx:jar:5.1.0.RELEASE:compile
pom.xml
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
</dependencies>
MVC
Model:-
Applications business logic is contained within the model and is responsible for maintaining data.
View: - It represents the user interface, with which the end user communicates. In short all the user
interface logic is contained within the VIEW
Controller:-It is the controller that answers to user actions. Based on the user actions, the respective
controller responds within the model and chooses a view to render that display the user interface. The
user input logic is contained with-in the controller
Spring Web MVC
The DispatcherServlet
The
DispatcherServlet
is an actual Servlet
(it inherits from the
HttpServlet base
class), and as such is
declared in your web
application
● Any incoming request that comes to the web
application will be sent to Front Controller
(Dispatcher Servlet)
● Front Controller decides to whom (Controller) it
has to hand over the request, based on the
request headers.
● Controller that took the request, processes the
request, by sending it to suitable service class.
● After all processing is done, Controller receives
the model from the Service or Data Access layer.
● Controller sends the model to the Front Controller
(Dispatcher Servlet).
● Dispatcher servlet finds the view template, using
view resolver and send the model to it.
● Using View template, model and view page is build
and sent back to the Front Controller.
● Front controller sends the constructed view page
to the browser to render it for the user requested.
Web.xml (No need in Java config)
<web-app>
<servlet>
<servlet-name>example</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>example</servlet-name>
<url-pattern>/example/*</url-pattern>
</servlet-mapping>
</web-app>
Root Config Classes are actually used to
Create Beans which are Application Specific
and which needs to be available for Filters (As
Filters are not part of Servlet).
Servlet Config Classes are actually used to
Create Beans which are DispatcherServlet
specific such as ViewResolvers,
ArgumentResolvers, Interceptor, etc.
Root Config Classes will be loaded first and
then Servlet Config Classes will be loaded.
Root Config Classes will be the Parent Context
and it will create a ApplicationContext
instance. Where as Servlet Config Classes will
be the Child Context of the Parent Context and
it will create a WebApplicationContext instance.
package hms.config.spring.mvc;
import hms.config.hibernate.AppContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{AppContext.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebMVCConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
Recommended way to set up Spring MVC application
Spring MVC Configuration
package hms.config.spring.mvc;
import ...
@Configuration
@EnableWebMvc
@ComponentScans({
@ComponentScan("hms.controller"),
@ComponentScan("dao"),
@ComponentScan("hms.service")
})
public class WebMVCConfig implements WebMvcConfigurer {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/pages/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
Spring MVC Configuration continue
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry
.addResourceHandler("/resources/**")
.addResourceLocations("/resources/");
}
}
For example – the following line will serve all requests for resources coming in with a public
URL pattern like “/resources/**” by searching in the “/resources/” directory under the root
folder in our application.
<mvc:resources mapping="/resources/**" location="/resources/" />
Bean overview
A Spring IoC container manages one or more beans. These beans are created
with the configuration metadata that you supply to the container, for example, in
the form of XML definitions.
The objects that form the backbone of application and that are managed by the
Spring IoC container are called beans
<!-- A simple bean definition -->
<bean id = "..." class = "...">
<!-- collaborators and configuration for this bean go here -->
</bean>
Basic annotations in spring 5
@Controller
public class CourseController {
private String returnPage;
@Autowired
private CourseService courseService;
@GetMapping("/advanced-course-management")
String getAdvancedCoursePage(Model model) {
model.addAttribute("allResults", courseService.getAllResults());
return "course/input/advanced-course";
}
@PostMapping("/add-result")
String addResult(@RequestParam("result") String result) {
courseService.addResult(result);
return "redirect:advanced-course-management";
}
@PostMapping("/course-add")
String addCourse(@ModelAttribute Course course) {
courseService.addCourse(course);
return returnPage;
}
Spring Annotations
@Component : This is a general-purpose stereotype annotation indicating that
the class is a spring component.
Spring Annotations
use the @RequestMapping annotation to map URL
● @GetMapping = @RequestMapping(method = RequestMethod.GET)
● @PostMapping = @RequestMapping(method = RequestMethod.POST)
● @PutMapping
● @DeleteMapping
● @PatchMapping
Hibernate
Hibernate ORM
Hibernate ORM is an object-relational mapping tool for the Java programming
language. It provides a framework for mapping an object-oriented domain model
to a relational database
Hibernate's primary feature is mapping from Java classes to database tables, and
mapping from Java data types to SQL data types.
What is ORM ?
ORM = Object-
relational mapping
Advantages of ORM
● Speeding development
● No need to deal with database implementations
● Efficient
● DB independence
Hibernate Overview
● Initial release : 23 May 2001; 17 years ago
● Hibernate 5.2 and later versions require at least Java 1.8 and JDBC 4.2.
○ I used 5.3.5.Final
● Hibernate does not require an application server to operate.
Java Database Connectivity (JDBC) is an application programming
interface (API) for the programming language Java
The Java Persistence API (JPA) is a Java application programming
interface specification that describes the management of relational
data in applications using Java Platform, Standard Edition and Java
Platform, Enterprise Edition.
Let’s handover Hibernate to Spring
The benefits of using the Spring Framework to create ORM DAOs include:
1. Easier testing
2. Common data access exceptions
a. Spring can wrap exceptions from ORM tool, converting them from proprietary (potentially
checked) exceptions to a common runtime DataAccessException hierarchy
3. General resource management
a. Spring application contexts can handle the location and configuration of Hibernate
SessionFactory instances, JPA EntityManagerFactory instances, JDBC DataSource instances,
and other related resources.
b. This makes these values easy to manage and change.
c. Spring offers efficient, easy, and safe handling of persistence resources.
d. Spring makes it easy to create and bind a Session to the current thread transparently, by
exposing a current Session through the Hibernate SessionFactory.
Source : https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html
pom.xml
<dependencies>
<!-- Spring MVC Dependency -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
<!-- Spring ORM -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>5.1.0.RELEASE</version>
</dependency>
</dependencies>
SessionFactory
● SessionFactory is an interface
● SessionFactory can be created by providing Configuration object, which will contain all DB
related property details pulled from either hibernate.cfg.xml file or hibernate.properties file.
○ @Autowired
○ protected SessionFactory sessionFactory;
● SessionFactory is a factory for Session objects.
○ Session session = sessionFactory.getCurrentSession()
SessionFactory
We can create one SessionFactory implementation per database in any application.
If your application is referring to multiple databases, then you need to create one
SessionFactory per database.
The SessionFactory is a heavyweight object; it is usually created during application start up
and kept for later use. The SessionFactory is a thread safe object and used by all the
threads of an application.
Basically, calling a method "thread-safe" means that even if multiple threads try to access it
simultaneously, nothing bad happens.
Session object
Session session = sessionFactory.getCurrentSession()
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
package hms.config.hibernate;
import ...
@Configuration
@PropertySource("classpath:database.properties")
@EnableTransactionManagement
@ComponentScans({
@ComponentScan(basePackages = {"hms"}),
@ComponentScan("dao")
})
public class AppContext {
@Autowired
private Environment environment;
@Bean
public LocalSessionFactoryBean sessionFactory() {
LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
sessionFactory.setDataSource(dataSource());
sessionFactory.setPackagesToScan("models");
sessionFactory.setHibernateProperties(hibernateProperties());
return sessionFactory;
}
SessionFactory Setup in Spring Container
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));
dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
return dataSource;
}
private Properties hibernateProperties() {
// Hibernate settings equivalent to hibernate.cfg.xml's properties
Properties settings = new Properties();
settings.put(DIALECT, environment.getRequiredProperty("hibernate.dialect"));
settings.put(SHOW_SQL, environment.getRequiredProperty("hibernate.show_sql"));
settings.put(CURRENT_SESSION_CONTEXT_CLASS, "thread");
settings.put(HBM2DDL_AUTO, environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
settings.put(FORMAT_SQL, environment.getRequiredProperty("hibernate.format_sql"));
return settings;
}
@Bean
public HibernateTransactionManager getTransactionManager() {
HibernateTransactionManager transactionManager = new HibernateTransactionManager();
transactionManager.setSessionFactory(sessionFactory().getObject());
return transactionManager;
}
}
database.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/available_courses?createDatabaseIfNotExist=true&useSSL=false
jdbc.username=user
jdbc.password=password
#Hibernate dialect specifies what type of SQL Query to be generated according to the given dialect like H2,
MySQL, etc.
hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect
hibernate.show_sql=true
hibernate.format_sql=true
#hibernate.hbm2ddl.auto, automatically validates or exports schema DDL to the database when the
SessionFactory is created.
hibernate.hbm2ddl.auto=update
#validate: validate the schema, makes no changes to the database.
update: update the schema.
create: creates the schema, destroying previous data.
create-drop: drop the schema when the SessionFactory is closed explicitly, typically when the application is
stopped.
package hms.config.spring.mvc;
import hms.config.hibernate.AppContext;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{AppContext.class};
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebMVCConfig.class};
}
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
Set up Spring MVC + Hibernate application
org.hibernate.query.Query;
The Hibernate Query object is used to retrieve data from database. We can use
either SQL or Hibernate Query Language (HQL).
A Query instance is obtained by calling Session.createQuery().
Query query = session.createQuery(“Query”);
The Query object is used to bind query parameters, limit query results and
execute the query.
Hibernate - Criteria Queries
Since Hibernate 5.2, the Hibernate Criteria API is deprecated and new
development is focused on the JPA Criteria API.
It not only enables us to write queries without doing raw SQL, but also gives us
some Object Oriented control over the queries, which is one of the main features
of Hibernate.
Hibernate - JPA Annotations
@Entity(name = "course")
public class Course {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private int duration;
private int cost;
@OneToMany(mappedBy = "course", cascade = CascadeType.ALL)
private List<CourseRequirements> requirements = new ArrayList<>();
//getters and setters
}
Example project : Course suggestion system
Courses
Requirements
Students
Related Technologies
Client Side
Server Side
ER-Diagram
Relational Schema
Use-Case Diagram
Project Structure
Demo
Thank you

More Related Content

What's hot

Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC frameworkMohit Gupta
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depthVinay Kumar
 
Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture TutorialJava Success Point
 
Java spring framework
Java spring frameworkJava spring framework
Java spring frameworkRajiv Gupta
 
Building web applications with Java & Spring
Building web applications with Java & SpringBuilding web applications with Java & Spring
Building web applications with Java & SpringDavid Kiss
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCHitesh-Java
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsGuy Nir
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkRajind Ruparathna
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlArjun Thakur
 

What's hot (20)

Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture Tutorial
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
 
Building web applications with Java & Spring
Building web applications with Java & SpringBuilding web applications with Java & Spring
Building web applications with Java & Spring
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Spring database - part2
Spring database -  part2Spring database -  part2
Spring database - part2
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 

Similar to Spring MVC 5 & Hibernate 5 Integration

Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
Sprint Portlet MVC Seminar
Sprint Portlet MVC SeminarSprint Portlet MVC Seminar
Sprint Portlet MVC SeminarJohn Lewis
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoasZeid Hassan
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Spring Basics
Spring BasicsSpring Basics
Spring BasicsEmprovise
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsmichaelaaron25322
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorialvinayiqbusiness
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET PresentationRasel Khan
 
Struts & spring framework issues
Struts & spring framework issuesStruts & spring framework issues
Struts & spring framework issuesPrashant Seth
 
Developing Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring toolsDeveloping Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring toolsSathish Chittibabu
 
A report on mvc using the information
A report on mvc using the informationA report on mvc using the information
A report on mvc using the informationToushik Paul
 
Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applicationselliando dias
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample ChapterSyed Shahul
 

Similar to Spring MVC 5 & Hibernate 5 Integration (20)

Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Sprint Portlet MVC Seminar
Sprint Portlet MVC SeminarSprint Portlet MVC Seminar
Sprint Portlet MVC Seminar
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
 
Spring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applicationsSpring data jpa are used to develop spring applications
Spring data jpa are used to develop spring applications
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorial
 
Spring mvc 2.0
Spring mvc 2.0Spring mvc 2.0
Spring mvc 2.0
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
 
MVC
MVCMVC
MVC
 
Spring tutorial
Spring tutorialSpring tutorial
Spring tutorial
 
Struts & spring framework issues
Struts & spring framework issuesStruts & spring framework issues
Struts & spring framework issues
 
Developing Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring toolsDeveloping Agile Java Applications using Spring tools
Developing Agile Java Applications using Spring tools
 
Asp.net control
Asp.net controlAsp.net control
Asp.net control
 
A report on mvc using the information
A report on mvc using the informationA report on mvc using the information
A report on mvc using the information
 
Struts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web ApplicationsStruts An Open-source Architecture for Web Applications
Struts An Open-source Architecture for Web Applications
 
Java spring ppt
Java spring pptJava spring ppt
Java spring ppt
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample Chapter
 
Session 1
Session 1Session 1
Session 1
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
 

Recently uploaded

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxShobhayan Kirtania
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...Sapna Thakur
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 

Recently uploaded (20)

Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
The byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptxThe byproduct of sericulture in different industries.pptx
The byproduct of sericulture in different industries.pptx
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
BAG TECHNIQUE Bag technique-a tool making use of public health bag through wh...
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

Spring MVC 5 & Hibernate 5 Integration

  • 1. Spring + Hibernate Presenter : Majurageerthan Arumugathasan
  • 5. Wait…? What is a Framework ? A framework is a reusable, “semi-complete” application that can be specialized to produce custom applications [Johnson and Foote, 1988].
  • 6. Pros And Cons Of Using Web Frameworks! Positive Negative Efficiency Lack of option to modify core behavior Security Limitation Cost You learn the framework, not the language Support source: https://www.vizteams.com/blog/advantages-and-disadvantages-of-frameworks/
  • 7.
  • 9. Spring Framework Overview ● The term "Spring" means different things in different contexts. ● The Spring Framework is a lightweight solution and a potential one-stop- shop for building your enterprise-ready applications. ● Initial release : 1 October 2002; 16 years ago ● Spring Framework 5.1 ○ requires JDK 8 or higher ○ Java EE 7 level (e.g. Servlet 3.1+, JPA 2.1+) as a minimum Source : https://docs.spring.io/spring/docs/current/spring-framework- reference/overview.html
  • 10. Features ● Core technologies: dependency injection, events, resources, i18n, validation, data binding, type conversion, SpEL, AOP. ● Testing: mock objects, TestContext framework, Spring MVC Test, WebTestClient. ● Data Access: transactions, DAO support, JDBC, ORM, Marshalling XML. ● Spring MVC and Spring WebFlux web frameworks. ● Integration: remoting, JMS, JCA, JMX, email, tasks, scheduling, cache. ● Languages: Kotlin, Groovy, dynamic languages. Source : https://spring.io/projects/spring-framework#overview
  • 11. Introduction to the Spring Framework The Spring Framework consists of features organized into about 20 modules.
  • 12. Core Technologies Configuration metadata represents how you as an application developer tell the Spring container to instantiate, configure, and assemble the objects in your application. Configuration metadata is traditionally supplied in a simple and intuitive XML format.
  • 13. XML-based configuration <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="accountDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaAccountDao"> <!-- additional collaborators and configuration for this bean go here --> </bean> <bean id="itemDao" class="org.springframework.samples.jpetstore.dao.jpa.JpaItemDao"> <!-- additional collaborators and configuration for this bean go here --> </bean> <!-- more bean definitions for data access objects go here -->
  • 14.
  • 15. XML-based metadata is not the only allowed form of configuration metadata Annotation-based configuration: Spring 2.5 introduced support for annotation-based configuration metadata. Java-based configuration: Starting with Spring 3.0, many features provided by the Spring JavaConfig project became part of the core Spring Framework
  • 16. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring- beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc- 4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring- context-4.0.xsd"> <context:component-scan base-package="hms.controller" /> <context:component-scan base-package="dao" /> <context:component-scan base-package="hms.service" /> <mvc:annotation-driven /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans> XML-based configuration
  • 17. package hms.config.spring.mvc; @Configuration @EnableWebMvc @ComponentScans({ @ComponentScan("hms.controller"), @ComponentScan("dao"), @ComponentScan("hms.service") }) public class WebMVCConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/pages/"); viewResolver.setSuffix(".jsp"); return viewResolver; } } Java-based configuration
  • 18. Spring Java Configuration Advantages 1. Easy to understand 2. Java is type safe. Compiler will report issues if you are configuring right bean class qualifiers. 3. XML based on configuration can quickly grow big. 4. Search is much simpler, refactoring will be easier. Finding a bean definition will be far easier. 5. etc,etc…….
  • 21. Spring Web MVC dependencies { provided("javax.servlet:javax.servlet-api:4.0.1") compile(project(":spring-aop")) compile(project(":spring-beans")) compile(project(":spring-context")) compile(project(":spring-core")) compile(project(":spring-expression")) compile(project(":spring-web")) } Source : https://github.com/spring-projects/spring-framework/blob/master/spring-webmvc/spring-webmvc.gradle
  • 22. mvn dependency:tree [INFO] --- maven-dependency-plugin:2.8:tree (default-cli) @ hms-orm --- [INFO] com.maju:hms-orm:jar:1.0-SNAPSHOT [INFO] +- org.springframework:spring-webmvc:jar:5.1.0.RELEASE:compile [INFO] | +- org.springframework:spring-aop:jar:5.1.0.RELEASE:compile [INFO] | +- org.springframework:spring-beans:jar:5.1.0.RELEASE:compile [INFO] | +- org.springframework:spring-context:jar:5.1.0.RELEASE:compile [INFO] | +- org.springframework:spring-core:jar:5.1.0.RELEASE:compile [INFO] | | - org.springframework:spring-jcl:jar:5.1.0.RELEASE:compile [INFO] | +- org.springframework:spring-expression:jar:5.1.0.RELEASE:compile [INFO] | - org.springframework:spring-web:jar:5.1.0.RELEASE:compile [INFO] +- org.springframework:spring-orm:jar:5.1.0.RELEASE:compile [INFO] | +- org.springframework:spring-jdbc:jar:5.1.0.RELEASE:compile [INFO] | - org.springframework:spring-tx:jar:5.1.0.RELEASE:compile
  • 23. pom.xml <dependencies> <!-- Spring MVC Dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.0.RELEASE</version> </dependency> </dependencies>
  • 24.
  • 25. MVC Model:- Applications business logic is contained within the model and is responsible for maintaining data. View: - It represents the user interface, with which the end user communicates. In short all the user interface logic is contained within the VIEW Controller:-It is the controller that answers to user actions. Based on the user actions, the respective controller responds within the model and chooses a view to render that display the user interface. The user input logic is contained with-in the controller
  • 27. The DispatcherServlet The DispatcherServlet is an actual Servlet (it inherits from the HttpServlet base class), and as such is declared in your web application
  • 28. ● Any incoming request that comes to the web application will be sent to Front Controller (Dispatcher Servlet) ● Front Controller decides to whom (Controller) it has to hand over the request, based on the request headers. ● Controller that took the request, processes the request, by sending it to suitable service class. ● After all processing is done, Controller receives the model from the Service or Data Access layer. ● Controller sends the model to the Front Controller (Dispatcher Servlet). ● Dispatcher servlet finds the view template, using view resolver and send the model to it. ● Using View template, model and view page is build and sent back to the Front Controller. ● Front controller sends the constructed view page to the browser to render it for the user requested.
  • 29. Web.xml (No need in Java config) <web-app> <servlet> <servlet-name>example</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>example</servlet-name> <url-pattern>/example/*</url-pattern> </servlet-mapping> </web-app>
  • 30. Root Config Classes are actually used to Create Beans which are Application Specific and which needs to be available for Filters (As Filters are not part of Servlet). Servlet Config Classes are actually used to Create Beans which are DispatcherServlet specific such as ViewResolvers, ArgumentResolvers, Interceptor, etc. Root Config Classes will be loaded first and then Servlet Config Classes will be loaded. Root Config Classes will be the Parent Context and it will create a ApplicationContext instance. Where as Servlet Config Classes will be the Child Context of the Parent Context and it will create a WebApplicationContext instance.
  • 31. package hms.config.spring.mvc; import hms.config.hibernate.AppContext; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{AppContext.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebMVCConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } } Recommended way to set up Spring MVC application
  • 32. Spring MVC Configuration package hms.config.spring.mvc; import ... @Configuration @EnableWebMvc @ComponentScans({ @ComponentScan("hms.controller"), @ComponentScan("dao"), @ComponentScan("hms.service") }) public class WebMVCConfig implements WebMvcConfigurer { @Bean public ViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/pages/"); viewResolver.setSuffix(".jsp"); return viewResolver; }
  • 33. Spring MVC Configuration continue @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry .addResourceHandler("/resources/**") .addResourceLocations("/resources/"); } } For example – the following line will serve all requests for resources coming in with a public URL pattern like “/resources/**” by searching in the “/resources/” directory under the root folder in our application. <mvc:resources mapping="/resources/**" location="/resources/" />
  • 34. Bean overview A Spring IoC container manages one or more beans. These beans are created with the configuration metadata that you supply to the container, for example, in the form of XML definitions. The objects that form the backbone of application and that are managed by the Spring IoC container are called beans <!-- A simple bean definition --> <bean id = "..." class = "..."> <!-- collaborators and configuration for this bean go here --> </bean>
  • 35.
  • 36. Basic annotations in spring 5 @Controller public class CourseController { private String returnPage; @Autowired private CourseService courseService; @GetMapping("/advanced-course-management") String getAdvancedCoursePage(Model model) { model.addAttribute("allResults", courseService.getAllResults()); return "course/input/advanced-course"; } @PostMapping("/add-result") String addResult(@RequestParam("result") String result) { courseService.addResult(result); return "redirect:advanced-course-management"; } @PostMapping("/course-add") String addCourse(@ModelAttribute Course course) { courseService.addCourse(course); return returnPage; }
  • 37. Spring Annotations @Component : This is a general-purpose stereotype annotation indicating that the class is a spring component.
  • 38. Spring Annotations use the @RequestMapping annotation to map URL ● @GetMapping = @RequestMapping(method = RequestMethod.GET) ● @PostMapping = @RequestMapping(method = RequestMethod.POST) ● @PutMapping ● @DeleteMapping ● @PatchMapping
  • 39.
  • 41. Hibernate ORM Hibernate ORM is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database Hibernate's primary feature is mapping from Java classes to database tables, and mapping from Java data types to SQL data types.
  • 42. What is ORM ? ORM = Object- relational mapping
  • 43. Advantages of ORM ● Speeding development ● No need to deal with database implementations ● Efficient ● DB independence
  • 44. Hibernate Overview ● Initial release : 23 May 2001; 17 years ago ● Hibernate 5.2 and later versions require at least Java 1.8 and JDBC 4.2. ○ I used 5.3.5.Final ● Hibernate does not require an application server to operate.
  • 45. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java The Java Persistence API (JPA) is a Java application programming interface specification that describes the management of relational data in applications using Java Platform, Standard Edition and Java Platform, Enterprise Edition.
  • 46. Let’s handover Hibernate to Spring The benefits of using the Spring Framework to create ORM DAOs include: 1. Easier testing 2. Common data access exceptions a. Spring can wrap exceptions from ORM tool, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy 3. General resource management a. Spring application contexts can handle the location and configuration of Hibernate SessionFactory instances, JPA EntityManagerFactory instances, JDBC DataSource instances, and other related resources. b. This makes these values easy to manage and change. c. Spring offers efficient, easy, and safe handling of persistence resources. d. Spring makes it easy to create and bind a Session to the current thread transparently, by exposing a current Session through the Hibernate SessionFactory. Source : https://docs.spring.io/spring-framework/docs/current/spring-framework-reference/data-access.html
  • 47. pom.xml <dependencies> <!-- Spring MVC Dependency --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>5.1.0.RELEASE</version> </dependency> <!-- Spring ORM --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>5.1.0.RELEASE</version> </dependency> </dependencies>
  • 48. SessionFactory ● SessionFactory is an interface ● SessionFactory can be created by providing Configuration object, which will contain all DB related property details pulled from either hibernate.cfg.xml file or hibernate.properties file. ○ @Autowired ○ protected SessionFactory sessionFactory; ● SessionFactory is a factory for Session objects. ○ Session session = sessionFactory.getCurrentSession()
  • 49. SessionFactory We can create one SessionFactory implementation per database in any application. If your application is referring to multiple databases, then you need to create one SessionFactory per database. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. The SessionFactory is a thread safe object and used by all the threads of an application. Basically, calling a method "thread-safe" means that even if multiple threads try to access it simultaneously, nothing bad happens.
  • 50. Session object Session session = sessionFactory.getCurrentSession() 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
  • 51. package hms.config.hibernate; import ... @Configuration @PropertySource("classpath:database.properties") @EnableTransactionManagement @ComponentScans({ @ComponentScan(basePackages = {"hms"}), @ComponentScan("dao") }) public class AppContext { @Autowired private Environment environment; @Bean public LocalSessionFactoryBean sessionFactory() { LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean(); sessionFactory.setDataSource(dataSource()); sessionFactory.setPackagesToScan("models"); sessionFactory.setHibernateProperties(hibernateProperties()); return sessionFactory; } SessionFactory Setup in Spring Container
  • 52. @Bean public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName")); dataSource.setUrl(environment.getRequiredProperty("jdbc.url")); dataSource.setUsername(environment.getRequiredProperty("jdbc.username")); dataSource.setPassword(environment.getRequiredProperty("jdbc.password")); return dataSource; } private Properties hibernateProperties() { // Hibernate settings equivalent to hibernate.cfg.xml's properties Properties settings = new Properties(); settings.put(DIALECT, environment.getRequiredProperty("hibernate.dialect")); settings.put(SHOW_SQL, environment.getRequiredProperty("hibernate.show_sql")); settings.put(CURRENT_SESSION_CONTEXT_CLASS, "thread"); settings.put(HBM2DDL_AUTO, environment.getRequiredProperty("hibernate.hbm2ddl.auto")); settings.put(FORMAT_SQL, environment.getRequiredProperty("hibernate.format_sql")); return settings; } @Bean public HibernateTransactionManager getTransactionManager() { HibernateTransactionManager transactionManager = new HibernateTransactionManager(); transactionManager.setSessionFactory(sessionFactory().getObject()); return transactionManager; } }
  • 53. database.properties jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/available_courses?createDatabaseIfNotExist=true&useSSL=false jdbc.username=user jdbc.password=password #Hibernate dialect specifies what type of SQL Query to be generated according to the given dialect like H2, MySQL, etc. hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect hibernate.show_sql=true hibernate.format_sql=true #hibernate.hbm2ddl.auto, automatically validates or exports schema DDL to the database when the SessionFactory is created. hibernate.hbm2ddl.auto=update #validate: validate the schema, makes no changes to the database. update: update the schema. create: creates the schema, destroying previous data. create-drop: drop the schema when the SessionFactory is closed explicitly, typically when the application is stopped.
  • 54. package hms.config.spring.mvc; import hms.config.hibernate.AppContext; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{AppContext.class}; } @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebMVCConfig.class}; } @Override protected String[] getServletMappings() { return new String[]{"/"}; } } Set up Spring MVC + Hibernate application
  • 55. org.hibernate.query.Query; The Hibernate Query object is used to retrieve data from database. We can use either SQL or Hibernate Query Language (HQL). A Query instance is obtained by calling Session.createQuery(). Query query = session.createQuery(“Query”); The Query object is used to bind query parameters, limit query results and execute the query.
  • 56. Hibernate - Criteria Queries Since Hibernate 5.2, the Hibernate Criteria API is deprecated and new development is focused on the JPA Criteria API. It not only enables us to write queries without doing raw SQL, but also gives us some Object Oriented control over the queries, which is one of the main features of Hibernate.
  • 57. Hibernate - JPA Annotations @Entity(name = "course") public class Course { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; private String name; private int duration; private int cost; @OneToMany(mappedBy = "course", cascade = CascadeType.ALL) private List<CourseRequirements> requirements = new ArrayList<>(); //getters and setters }
  • 58. Example project : Course suggestion system Courses Requirements Students
  • 64. Demo