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
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 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.xmlThis 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.xml5) Display the message in the JSP page
hellopage.jspMessage is: ${message}<groupId>com.javaspotgroupId><artifactId>SpringMVCartifactId> Spring 3 MVC Multiple Controller Example1) 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 componentshellopage.jsp
Message is: ${message}errorpage.jsp${message}3) Index page
.index.jspspring 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