OfferTransform Your Career with Expert-Led IT Training. Flat discounts active!Explore Now
OnlineITGuru Logo
WEEKEND SPECIAL - UPTO 60% OFF
AI & Machine Learning

ORM Frameworks

Last updated on Jun 15, 2020

Copy Link:
ORM Frameworks
ORM Frameworks

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
CREATE TABLE  "EMP558" (    "ID" NUMBER(10,0) NOT NULL ENABLE, "NAME" VARCHAR2(255 CHAR), "SALARY" FLOAT(126), PRIMARY KEY ("ID") ENABLE ) / 2) Employee.java package com.javaspot; public class Employee { private int id; private String name; private float salary; //getters and setters } 3) employee.hbm.xml <?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="com.javaspot.Employee" table="emp558"> <id name="id"> <generator class="assigned"></generator> </id> <property name="name"></property> <property name="salary"></property> </class> </hibernate-mapping> 4) EmployeeDao.java package com.javaspot; import org.springframework.orm.hibernate3.HibernateTemplate; import java.util.*; public class EmployeeDao { HibernateTemplate template; public void setTemplate(HibernateTemplate template) { this.template = template; } //method to save employee public void saveEmployee(Employee e){ template.save(e); } //method to update employee public void updateEmployee(Employee e){ template.update(e); } //method to delete employee public void deleteEmployee(Employee e){ template.delete(e); } //method to return one employee of given id public Employee getById(int id){ Employee e=(Employee)template.get(Employee.class,id); return e; } //method to return all employees public List<Employee> getEmployees(){ List<Employee> list=new ArrayList<Employee>(); list=template.loadAll(Employee.class); return list; } } 5) applicationContext.xml File: applicationContext.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"  value="oracle.jdbc.driver.OracleDriver"></property> <property name="url" value="jdbc:oracle:thin:@localhost:1521:xe"></property> <property name="username" value="system"></property> <property name="password" value="oracle"></property> </bean> <bean id="mysessionFactory"  class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"></property> <property name="mappingResources"> <list> <value>employee.hbm.xml</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> </props> </property> </bean> <bean id="template" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="mysessionFactory"></property> </bean> <bean id="d" class="com.javaspot.EmployeeDao"> <property name="template" ref="template"></property> </bean> </beans> 6) InsertTest.java package com.javaspot; import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; public class InsertTest { public static void main(String[] args) { Resource r=new ClassPathResource("applicationContext.xml"); BeanFactory factory=new XmlBeanFactory(r); EmployeeDao dao=(EmployeeDao)factory.getBean("d"); Employee e=new Employee(); e.setId(114); e.setName("varun"); e.setSalary(50000); dao.saveEmployee(e); } } <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop> <prop key="hibernate.hbm2ddl.auto">update</prop> <prop key="hibernate.show_sql">true</prop> </props>
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
  1. create Account.java file
  2. create Account.xml file
  3. create AccountDao.java file
  4. create persistence.xml file
  5. create applicationContext.xml file
  6. 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 file

This 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 Example
1) 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 components
hellopage.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
Spring MVC File Upload Steps (Extra than MVC) 1) Add commons-io and fileupload.jar files 2) Add entry of CommonsMultipartResolver in spring-servlet.xml <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> 3) Create form to submit file. Method name must be "post" and enctype "multiple/form-data". <form action="savefile" method="post" enctype="multipart/form-data"> Select File: <input type="file" name="file"/> <input type="submit" value="Upload File"/> </form> 4) Use CommonsMultipartFile class in Controller. @RequestMapping(value="/savefile",method=RequestMethod.POST) public ModelAndView upload(@RequestParam CommonsMultipartFile file,HttpSession session){ String path=session.getServletContext().getRealPath("/"); String filename=file.getOriginalFilename(); System.out.println(path+" "+filename); try{ byte barr[]=file.getBytes(); BufferedOutputStream bout=new BufferedOutputStream( new FileOutputStream(path+"/"+filename)); bout.write(barr); bout.flush(); bout.close(); }catch(Exception e){System.out.println(e);} return new ModelAndView("upload-success","filename",path+"/"+filename); } 5) Display image in JSP. <h1>Upload Success</h1> <img src="${filename}"/>   Spring MVC File Upload Example  Create images directory index.jsp <a href="/uploadform">Upload Image</a> Emp.java package com.javaspot; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.commons.CommonsMultipartFile; import org.springframework.web.servlet.ModelAndView; @Controller public class HelloController { private static final String UPLOAD_DIRECTORY ="/images"; @RequestMapping("uploadform") public ModelAndView uploadForm(){ return new ModelAndView("uploadform"); } @RequestMapping(value="savefile",method=RequestMethod.POST) public ModelAndView saveimage( @RequestParam CommonsMultipartFile file, HttpSession session) throws Exception{ ServletContext context = session.getServletContext(); String path = context.getRealPath(UPLOAD_DIRECTORY); String filename = file.getOriginalFilename(); System.out.println(path+" "+filename); byte[] bytes = file.getBytes(); BufferedOutputStream stream =new BufferedOutputStream(new FileOutputStream( new File(path + File.separator + filename))); stream.write(bytes); stream.flush(); stream.close(); return new ModelAndView("uploadform","filesuccess","File successfully saved!"); } } 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>/</url-pattern> </servlet-mapping> </web-app> 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"></context:component-scan> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/> </beans> uploadform.jsp Here form must be method="post" and enctype="multipart/form-data". <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <!DOCTYPE html> <html> <head> <title>Image File Upload</title> </head> <body> <h1>File Upload Example - Javaspot</h1> <h3 style="color:red">${filesuccess}</h3> <form:form method="post" action="savefile" enctype="multipart/form-data"> <p><label for="image">Choose Image</label></p> <p><input name="file" id="fileToUpload" type="file" /></p> <p><input type="submit" value="Upload"></p> </form:form> </body> </html>

Why Choose Us

Master Your Future with OnlineITGuru

We don't just provide courses; we build careers. From expert-led live training to dedicated placement support, discover why thousands of professionals trust us for their digital transformation journey.

200+

Partner Companies

$120K

Highest Package

75%

Average Hike

98%

Placement Rate

Reliable Career Partners

Google
Microsoft
Amazon
Meta
Netflix
Apple