Double Bonanza Offer - Upto 30% Off + 1 Self Paced Course Free | OFFER ENDING IN: 0 D 0 H 0 M 0 S

Log In to start Learning

Login via

Post By Admin Last Updated At 2020-06-15
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 hibernateThe 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.javapackage com.javaspot;public class Employee {private int id;private String name;private float salary;//getters and setters}3) employee.hbm.xml<class name="com.javaspot.Employee" table="emp558">class="assigned">class>4) EmployeeDao.javapackage 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 employeepublic void saveEmployee(Employee e){template.save(e);}//method to update employeepublic void updateEmployee(Employee e){template.update(e);}//method to delete employeepublic void deleteEmployee(Employee e){template.delete(e);}//method to return one employee of given idpublic Employee getById(int id){Employee e=(Employee)template.get(Employee.class,id);return e;}//method to return all employeespublic List getEmployees(){List list=new ArrayList();list=template.loadAll(Employee.class);return list;}}5) applicationContext.xmlFile: applicationContext.xmlclass="org.apache.commons.dbcp.BasicDataSource">class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">employee.hbm.xmlorg.hibernate.dialect.Oracle9Dialectupdatetrueclass="org.springframework.orm.hibernate3.HibernateTemplate">class="com.javaspot.EmployeeDao">6) InsertTest.javapackage 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);}}org.hibernate.dialect.Oracle9Dialectupdatetrue
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 operatorSystem.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 operatorSystem.out.println(parser.parseExpression("true and true").getValue());//Relational operatorSystem.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.javapublic 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.javaimport 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.jspclick2) Create the controller classThe @Controller annotation.The @Requestmapping annotationWelcomeWorldController.javapackage com.javaspot;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic 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.xmlspringclass>org.springframework.web.servlet.DispatcherServletclass>1spring*.html4) 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.xmlpackage="com.javaspot" />class="org.springframework.web.servlet.view.InternalResourceViewResolver">
5) Display the message in the JSP page
 hellopage.jspMessage is: ${message}<groupId>com.javaspotgroupId><artifactId>SpringMVCartifactId> Spring 3 MVC Multiple Controller Example
1) Controller Classes
 WelcomeWorldController.javapackage com.javaspot;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class WelcomeWorldController {@RequestMapping("/welcome")public ModelAndView welcomeWorld() {String message = "WELCOME SPRING MVC";return new ModelAndView("welcomepage", "message", message);}}
2) View components
 hellopage.jspMessage is: ${message} welcomepage.jspMessage is: ${message}
3) Index page
 index.jspclick|clickSpring MVC Request Response ExampleController ClassHelloWorldController.javapackage 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;@Controllerpublic 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}
 3) Index page
.index.jspName:
Password:
spring MVC File Upload ExampleRequired Jar filesTo 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 files2) 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 Successh1><img src="${filename}"/> Spring MVC File Upload Example Create images directoryindex.jsp<a href="uploadform">Upload Imagea>Emp.javapackage 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;@Controllerpublic 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.xmlspringclass>org.springframework.web.servlet.DispatcherServletclass>1spring/spring-servlet.xmlpackage="com.javaspot">class="org.springframework.web.servlet.view.InternalResourceViewResolver">class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>uploadform.jspHere form must be method="post" and enctype="multipart/form-data".<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>Image File Upload

File Upload Example - Javaspot

${filesuccess}

for="image">Choose Image