ORM Frameworks
Last updated on Jun 15, 2020
Spring gives API to effectively incorporate Spring with ORM structures, for example, Hibernate, JPA(Java Persistence API), JDO(Java Data Objects), Oracle Toplink and iBATIS.
Advantage of ORM Frameworks with Spring
- Less coding is required
- Easy to test
- Better exception handling Integrated transaction management
Hibernate and Spring Integration
We can just incorporate rest application with spring application hibernate structure, we give all the database data hibernate.cfg.xml document.
Yet, in the event that we will incorporate the sleep application with spring, we don't have to make the hibernate.cfg.xml record.We can give all the data in the applicationContext.xml document.
Favorable position of Spring system with hibernate The Spring structure gives HibernateTemplate class, so you don't have to take after such a large number of steps like make Configuration, BuildSessionFactory, Session, starting and submitting exchange.JAVA Tutorial Video
[embed]https://www.youtube.com/watch?v=UbpbqqIw_3Q&t=1725s[/embed]Methods of HibernateTemplate class
| No. | Method |
| 1) | void persist(Object entity) |
| 2) | Serializable save(Object entity) |
| 3) | void saveOrUpdate(Object entity) |
| 4) | void update(Object entity) |
| 5) | void delete(Object entity) |
| 6) | Object get(Class entityClass, Serializable id) |
| 7) | Object load(Class entityClass, Serializable id) |
| 8) | List loadAll(Class entityClass) |
Steps
- create table in the database
- create applicationContext.xml file
- create Employee.java file
- create employee.hbm.xml file
- create EmployeeDao.java file
- create InsertTest.java file
- create the table in the database
Spring Data JPA
Spring Data JPA API gives JpaTemplate class to coordinate spring application with JPA.
JPA (Java Persistent API) is the sun determination for holding on objects in the endeavor application. It is at present utilized as the substitution for complex element beans.
The usage of JPA determination are given by numerous merchants
- Hibernate
- Toplink
- iBatis
- OpenJPA
Advantage of Spring JpaTemplate
You don't have to write the prior code and then afterward code for continuing, refreshing, erasing or seeking article, for example, making Persistence occurrence, making EntityManagerFactory case, making Entity Transaction case, making Entity Manager occasion, commiting Entity Transaction case and shutting Entity Manager.
Example of Spring and JPA Integration
- create Account.java file
- create Account.xml file
- create AccountDao.java file
- create persistence.xml file
- create applicationContext.xml file
- create AccountsClient.java file
Spring Expression Language (SPEL)
SpEL is an expression dialect supporting the elements of questioning and controlling a protest diagram at runtime.
There are numerous articulation dialects accessible, for example, JSP EL, OGNL, MVEL and JBoss EL. SpEL gives some extra elements, for example, strategy summon and string templating usefulness.
SpEL API
- Expression interface
- SpelExpression class
- ExpressionParser interface
- SpelExpressionParser class
- EvaluationContext interface
- StandardEvaluationContext class
Operators in SPEL
Examples of using operators in SPEL
import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; public class Test { public static void main(String[] args) { ExpressionParser parser = new SpelExpressionParser(); //arithmetic operator System.out.println(parser.parseExpression("'Welcome SPEL'+'!'").getValue()); System.out.println(parser.parseExpression("10 * 10/2").getValue()); System.out.println(parser.parseExpression("'Today is: '+ new java.util.Date()").getValue()); //logical operator System.out.println(parser.parseExpression("true and true").getValue()); //Relational operator System.out.println(parser.parseExpression("'sonoo'.length()==5").getValue()); } }Variable in SPEL | StandardEvaluationContext:
Variable in a SPEL is it can store a value in a variable and that is used in method and call the method.For working on this we must use Standard Evaluation Context class.
Example of Using variable in SPEL
Calculation.java public class Calculation { private int number; public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public int cube(){ return number*number*number; } } Test.java import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; public class Test { public static void main(String[] args) { Calculation calculation=new Calculation(); StandardEvaluationContext context=new StandardEvaluationContext(calculation); ExpressionParser parser = new SpelExpressionParser(); parser.parseExpression("number").setValue(context,"5"); System.out.println(calculation.cube()); }}
Spring MVC
Spring MVC instructional exercise gives an exquisite answer for utilize MVC in spring system by the assistance of DispatcherServlet.
In Spring Web MVC, DispatcherServlet class fills in as the front controller. It is dependable to deal with the stream of the spring mvc application.
The @Controller comment is utilized to stamp the class as the controller in Spring 3.
The @RequestMapping comment is utilized to outline ask for url.
Flow of Spring Web MVC:
Spring Web MVC Framework
Create the request page (optional)
Create the controller class
Provide the entry of controller in the web.xml file
Define the bean in the xml file
Display the message in the JSP page
Load the spring core and mvc jar files
Start server and deploy the project
Required Jar files or Maven Dependency
To run this example, you need to load:- Spring Core jar files
- Spring Web jar files
1) Create the request page (optional)
index.jsp <a href="/hello.html">click</a> 2) Create the controller class The @Controller annotation. The @Requestmapping annotation WelcomeWorldController.java package com.javaspot; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public classWelcomeWorldController { @RequestMapping("/hello") public ModelAndView helloWorld() { String message = "HELLO SPRING MVC HOW R U"; return new ModelAndView("hellopage", "message", message); } } 3) Provide the entry of controller in the web.xml file web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>*.html</url-pattern> </servlet-mapping> </web-app> 4) Define the bean in the xml fileThis is the essential setup record where we have to determine the ViewResolver and View parts.
The context:component-scan component characterizes the base-bundle where DispatcherServlet will look through the controller class.
Here, the InternalResourceViewResolver class is utilized for the ViewResolver.
The prefix+string returned by controller+suffix page will be conjured for the view part.
This xml document ought to be situated inside the WEB-INF index.
spring-servlet.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="com.javaspot" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> </beans>5) Display the message in the JSP page
hellopage.jsp Message is: ${message} <groupId>com.javaspot</groupId> <artifactId>SpringMVC</artifactId> Spring 3 MVC Multiple Controller Example1) Controller Classes
WelcomeWorldController.java package com.javaspot; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class WelcomeWorldController { @RequestMapping("/welcome") public ModelAndView welcomeWorld() { String message = "WELCOME SPRING MVC"; return new ModelAndView("welcomepage", "message", message); } }2) View components
hellopage.jsp Message is: ${message} welcomepage.jsp Message is: ${message}3) Index page
index.jsp <a href="/hello.html">click</a>| <a href="/welcome.html">click</a> Spring MVC Request Response Example Controller Class HelloWorldController.java package com.javaspot; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloWorldController { @RequestMapping("/hello") public ModelAndView helloWorld(HttpServletRequest request,HttpServletResponse res) { String name=request.getParameter("name"); String password=request.getParameter("password"); if(password.equals("admin")){ String message = "HELLO "+name; return new ModelAndView("hellopage", "message", message); } else{ return new ModelAndView("errorpage", "message","Sorry, username or password error"); } } } 2) View componentshellopage.jsp
Message is: ${message} errorpage.jsp ${message} <jsp:include page="/index.jsp"></jsp:include>3) Index page
.index.jsp <form action="hello.html" method="post"> Name:<input type="text" name="name"/><br/> Password:<input type="password" name="password"/><br/> <input type="submit" value="login"/> </form> spring MVC File Upload Example Required Jar files To run this example, you need to load:- Spring Core jar files
- Spring Web jar files
- commons-fileupload.jar and commons-io.jar file
