SlideShare a Scribd company logo
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 Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif
 
Spring MVC framework
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
Vinay Kumar
 
Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture Tutorial
Java Success Point
 
Java spring framework
Java spring frameworkJava spring framework
Java spring framework
Rajiv Gupta
 
Building web applications with Java & Spring
Building web applications with Java & SpringBuilding web applications with Java & Spring
Building web applications with Java & Spring
David Kiss
 
Spring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVCSpring - Part 4 - Spring MVC
Spring - Part 4 - Spring MVC
Hitesh-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 topics
Guy Nir
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
Dzmitry Naskou
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring 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
Tuna Tore
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
Harshit Choudhary
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Rajind 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 - MVC
Dzmitry Naskou
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
dasguptahirak
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
Emprovise
 
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
Arjun Thakur
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
Bozhidar Bozhanov
 

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 Seminar
John Lewis
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
Zeid Hassan
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Spring Basics
Spring BasicsSpring Basics
Spring Basics
Emprovise
 
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
michaelaaron25322
 
Spring framework-tutorial
Spring framework-tutorialSpring framework-tutorial
Spring framework-tutorial
vinayiqbusiness
 
Spring mvc 2.0
Spring mvc 2.0Spring mvc 2.0
Spring mvc 2.0
Rudra Garnaik, PMI-ACP®
 
ASP.NET Presentation
ASP.NET PresentationASP.NET Presentation
ASP.NET Presentation
Rasel Khan
 
Spring tutorial
Spring tutorialSpring tutorial
Spring tutorial
Sanjoy Kumer Deb
 
Struts & spring framework issues
Struts & spring framework issuesStruts & spring framework issues
Struts & spring framework issues
Prashant 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 tools
Sathish Chittibabu
 
Asp.net control
Asp.net controlAsp.net control
Asp.net control
Paneliya Prince
 
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
Toushik 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
 
Java spring ppt
Java spring pptJava spring ppt
Java spring ppt
natashasweety7
 
Spring Live Sample Chapter
Spring Live Sample ChapterSpring Live Sample Chapter
Spring Live Sample ChapterSyed Shahul
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
Mindsmapped Consulting
 

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

June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
joachimlavalley1
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
Peter Windle
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
Mohd Adib Abd Muin, Senior Lecturer at Universiti Utara Malaysia
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
SACHIN R KONDAGURI
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
Jisc
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
timhan337
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
MysoreMuleSoftMeetup
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
Balvir Singh
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Atul Kumar Singh
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
BhavyaRajput3
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
Jisc
 

Recently uploaded (20)

June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Additional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdfAdditional Benefits for Employee Website.pdf
Additional Benefits for Employee Website.pdf
 
A Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in EducationA Strategic Approach: GenAI in Education
A Strategic Approach: GenAI in Education
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Chapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptxChapter 3 - Islamic Banking Products and Services.pptx
Chapter 3 - Islamic Banking Products and Services.pptx
 
"Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe..."Protectable subject matters, Protection in biotechnology, Protection of othe...
"Protectable subject matters, Protection in biotechnology, Protection of othe...
 
The approach at University of Liverpool.pptx
The approach at University of Liverpool.pptxThe approach at University of Liverpool.pptx
The approach at University of Liverpool.pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 
Honest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptxHonest Reviews of Tim Han LMA Course Program.pptx
Honest Reviews of Tim Han LMA Course Program.pptx
 
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
Mule 4.6 & Java 17 Upgrade | MuleSoft Mysore Meetup #46
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
Operation Blue Star - Saka Neela Tara
Operation Blue Star   -  Saka Neela TaraOperation Blue Star   -  Saka Neela Tara
Operation Blue Star - Saka Neela Tara
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Guidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th SemesterGuidance_and_Counselling.pdf B.Ed. 4th Semester
Guidance_and_Counselling.pdf B.Ed. 4th Semester
 
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCECLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
CLASS 11 CBSE B.St Project AIDS TO TRADE - INSURANCE
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
Supporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptxSupporting (UKRI) OA monographs at Salford.pptx
Supporting (UKRI) OA monographs at Salford.pptx
 

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