This presentation will explain about spring and hibernate integration based on Java config. moreover, this presentation has a detailed explanation of spring and hibernate integration.
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/
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
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…….
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
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>
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
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
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