Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Spring 4 Restful web services with Hibernate 4

Tags: import

In our last tutorial we’ve dealt with Spring 4 Restful web service, now we’re here continue the same with Hibernate 4.

Quick Setup & Requirements

Required Jars

  1. Spring 4.2.0.RELEASE
  2. jackson-annotations-2.6.3.jar
  3. jackson-core-2.6.3.jar
  4. jackson-databind-2.6.3.jar
  5. hibernate-release-4.3.10.Final

Project Structure

Spring 4 Restful web services with Hibernate 4
Spring 4 Restful web services with Hibernate 4

Spring MVC 4 Configuration

AppConfig.java

package com.expertwebindia.services;
import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

import com.expertwebindia.controllers.Test;

@Configuration 
@ComponentScan(basePackages = {"com.expertwebindia.controllers","com.expertwebindia.services"}) 
@EnableWebMvc   
public class AppConfig {  
    @Bean  
    public ViewResolver contentNegotiatingViewResolver(  
                    ContentNegotiationManager manager) {  
            List< ViewResolver > resolvers = new ArrayList< ViewResolver >();  
            
            //For JSP Views
            InternalResourceViewResolver r1 = new InternalResourceViewResolver();  
            r1.setPrefix("/WEB-INF/views/");  
            r1.setSuffix(".jsp");  
            r1.setViewClass(JstlView.class);  
            resolvers.add(r1);  
            
            //For JSON views 

            JsonViewResolver r2 = new JsonViewResolver();  
            resolvers.add(r2);  
            
            //For XML views 
            Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
            Jaxb2MarshallingXmlViewResolver jaxb2MarshallingXmlViewResolver =  new Jaxb2MarshallingXmlViewResolver(marshaller);
            resolvers.add(jaxb2MarshallingXmlViewResolver);
            
            ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();  
            resolver.setViewResolvers(resolvers);  
            resolver.setContentNegotiationManager(manager);  
            return resolver;  
    } 
} 

Defining ViewResolvers

We have two view resolvers here.

  1. For XML
  2. For JSON

Jaxb2MarshallingXmlViewResolver.java

package com.expertwebindia.services;
import java.util.Locale;
import org.springframework.oxm.Marshaller;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.xml.MarshallingView;

public class Jaxb2MarshallingXmlViewResolver implements ViewResolver {

private Marshaller marshaller;

public Jaxb2MarshallingXmlViewResolver(Marshaller marshaller) {
this.marshaller = marshaller;
}
public View resolveViewName(String viewName, Locale locale)
throws Exception {
MarshallingView view = new MarshallingView();
view.setMarshaller(marshaller);
return view;
}

}

JsonViewResolver.java

package com.expertwebindia.services;

import java.util.Locale;

import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

public class JsonViewResolver implements ViewResolver{

@Override
public View resolveViewName(String viewName, Locale locale) throws Exception {
MappingJackson2JsonView view = new MappingJackson2JsonView();
view.setPrettyPrint(true);
return view;
}

}

Configuring Dispatcher Servlet and Associating AppConfig

WebAppInitializer.java

package com.expertwebindia.services;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
ctx.setConfigLocation("/WEB-INF/dispatcher-servlet.xml");
Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}

Defining POJO class

Product POJO class is annotated with JAXB annotations to facilitate XML response. This POJO is also annotated with JPA annotations to treated as Hibernate Entity.

Product.java

package com.expertwebindia.beans;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@Entity
@Table(name="products")
@XmlRootElement(name="product")
public class Product {
 @Id
 @GeneratedValue(strategy=GenerationType.AUTO)
 private int id;
 private double price;
 private String name;
public Product() {
	super();
}
public Product(int id, String name,double price) {
	super();
	this.id = id;
	this.price = price;
	this.name = name;
}
@XmlElement
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
@XmlElement
public double getPrice() {
	return price;
}
public void setPrice(double price) {
	this.price = price;
}
@XmlElement
public String getName() {
	return name;
}
public void setName(String name) {
	this.name = name;
}
 
}


Defining DAO class

package com.expertwebindia.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.expertwebindia.beans.Product;
public class ProductDao {
@Autowired
private SessionFactory sessionFactory;

public SessionFactory getSessionFactory() {
return sessionFactory;
}

public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public List<Product> getProducts(){
Session session = sessionFactory.openSession();
Criteria criteria = session.createCriteria(Product.class);
List<Product> list = criteria.list();
return list;
}
public Product getProduct(int id){
Session session = sessionFactory.openSession();
Product product = (Product)session.get(Product.class, id);
return product;
}
}

Defining Controller for Rest Services

ProductService.java

package com.expertwebindia.services;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.expertwebindia.beans.Product;
import com.expertwebindia.beans.Stock;
import com.expertwebindia.dao.ProductDao;

@RestController
@RequestMapping("/services/product/")
public class ProductService {
    @Autowired
    private ProductDao dao;
    
    public ProductDao getDao() {
        return dao;
    }
    public void setDao(ProductDao dao) {
        this.dao = dao;
    }
    @RequestMapping(value = "/list", method = RequestMethod.GET)
       public ResponseEntity<List<Product>> listAllProducts() {  
             List productsList = new ArrayList<Product>();
             productsList = dao.getProducts();
             return new ResponseEntity<List<Product>>(productsList, HttpStatus.OK);
        }
   @RequestMapping(value = "/listXML", method = RequestMethod.GET,produces = "application/xml")
    public ResponseEntity<Stock> listProducts() { 
         Stock stock = new Stock();
         List<Product> productsList = new ArrayList<Product>();
         productsList = dao.getProducts();
         stock.setProducts(productsList);
        return new ResponseEntity<Stock>(stock, HttpStatus.OK);
    }

    @RequestMapping(value = "/getProduct/{id}", method = RequestMethod.GET,produces = "application/xml")
    public ResponseEntity<Product> getProduct(@PathVariable Integer id) { 
        System.out.println("ID=="+id);
        Product product = dao.getProduct(id); 
        return new ResponseEntity<Product>(product, HttpStatus.OK);
    }
       
     
}

Defining Beans using dispatcher-servlet.xml

dispatcher-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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/hibernatedb" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="packagesToScan" value="com.expertwebindia.beans" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="connection.pool_size">10</prop>

</props>
</property>
</bean>
<bean id="hibernateTransactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="productDao" class="com.expertwebindia.dao.ProductDao">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:annotation-driven transaction-manager="hibernateTransactionManager"/>
</beans>

Defining ContextLoaderListener in web.xml to create beans

<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
</context-param>

<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
</web-app>

Execution & Output

1)Single Product with XML response

http://localhost:9999/Spring4WebService/services/product/getProduct/3

Output

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <product>
      <id>3</id>
      <name>C003</name>
      <price>2300.0</price>
    </product>

2)List products with XML response

http://localhost:9999/Spring4WebService/services/product/listXML

Output

 <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <stock>
      <product>
        <id>1</id>
        <name>A001</name>
        <price>2000.0</price>
      </product>
      <product>
        <id>2</id>
        <name>B002</name>
        <price>1000.0</price>
      </product>
      <product>
        <id>3</id>
        <name>C003</name>
        <price>2300.0</price>
      </product>
    </stock>



This post first appeared on Expertwebindia|Online Web Solutions, please read the originial post: here

Share the post

Spring 4 Restful web services with Hibernate 4

×

Subscribe to Expertwebindia|online Web Solutions

Get updates delivered right to your inbox!

Thank you for your subscription

×