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.
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.
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) |
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>
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 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
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.
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.
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 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.
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;
}
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 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.
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
To run this example, you need to load:
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>
hellopage.jsp
Message is: ${message}
<groupId>com.javaspot</groupId>
<artifactId>SpringMVC</artifactId>
Spring 3 MVC Multiple Controller Example
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);
}
}
hellopage.jsp
Message is: ${message}
welcomepage.jsp
Message is: ${message}
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
Message is: ${message}
errorpage.jsp
${message}
<jsp:include page=”/index.jsp”></jsp:include>
.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 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>
Python is a dynamic interrupted language which is used in wide varieties of applications. It is very interactive object oriented and high-level programming language.
Tableau is a Software company that caters interactive data visualization products that provide Business Intelligence services. The company’s Head Quarters is in Seattle, USA.
Micro Strategy is one of the few independent and publicly trading Business Intelligence software provider in the market. The firm is operational in 27 Countries around the globe.
Pega Systems Inc. is a Cambridge, Massachusetts based Software Company. It is known for developing software for Customer Relationship Management (CRM) and Business process Management (BPM).
Workday specialises in providing Human Capital Management, Financial Management and payroll in online domain.It is a major web based ERP software vendor.
Power BI is business analytics service by Microsoft. With Power BI, end users can develop reports and dashboards without depending on IT staff or Database Administrator.