Spring REST JPA Entities Example

In this tutorial, we will directly expose JPA entities as JSON object so that there is not need to transform DTO objects to Entities.This tutorial is extension to below one which exposes DTO as JSON objects.

Spring 4 REST Hibernate CRUD Example

In this tutorial, we will see the following CRUD operations on Employee entity using Spring 4 REST Services using Hibernate JPA. The following are REST samples for each operation. Add Employee : http://localhost:8080/spring-rest-hibernate/rest/employee/add Update Employee:http://localhost:8080/spring-rest-hibernate/rest/employee/update…READ MORE

Customer JPA Entity is directly exposed as JSON  and has below CRUD operations:

  1. Add   : http://localhost:8080/spring-rest-hibernate/rest/customer/add
  2. Update : http://localhost:8080/spring-rest-hibernate/rest/customer/update
  3. All customers : http://localhost:8080/spring-rest-hibernate/rest/customer/all
  4. Get customer : http://localhost:8080/spring-rest-hibernate/rest/customer/1
  5. Delete: http://localhost:8080/spring-rest-hibernate/rest/customer/delete/1

 

  1. Create Project Structure like show below:Spring REST hibernate tutorial
  2. In this, Employee Services uses DTO and Customer Service uses Entity directly
  3. For Web.xml and mvcConfig.xml, Please refer to the above tutorial
  4. Create Customer Rest Controller :
    1. package org.javasavvy.spring.rest.conroller;
      
      import java.util.List;
      import org.apache.log4j.Logger;
      import org.javasavvy.spring.entity.Customer;
      import org.javasavvy.spring.rest.dto.StatusDTO;
      import org.javasavvy.spring.services.CustomerService;
      import org.springframework.beans.factory.annotation.Autowired;
      import org.springframework.beans.factory.annotation.Qualifier;
      import org.springframework.web.bind.annotation.GetMapping;
      import org.springframework.web.bind.annotation.PathVariable;
      import org.springframework.web.bind.annotation.RequestBody;
      import org.springframework.web.bind.annotation.RequestMapping;
      import org.springframework.web.bind.annotation.RequestMethod;
      import org.springframework.web.bind.annotation.RestController;
      
      @RestController
      @RequestMapping("/customer")
      public class CustomerController {
       
       Logger LOG = Logger.getLogger(CustomerController.class.getName());
       
       @Autowired(required=true)
       @Qualifier("customerService")
       private CustomerService customerService;
       
       @GetMapping("/{customerId}")
       public Customer getCustomers(@PathVariable("customerId") long customerId){
       
       return customerService.getCustomer(customerId);
       }
       @RequestMapping(value="/all",method=RequestMethod.GET)
       public List<Customer> allCustomers(){
       List<Customer> list = customerService.getAllCustomers();
       return list;
       }
       @RequestMapping(value="/update",method=RequestMethod.POST)
       public Customer editCustomer(@RequestBody Customer customer){
       customer = customerService.updateCustomer(customer);
       return customer;
       
       }
       @RequestMapping(value="/add",method=RequestMethod.POST)
       public Customer addCustomer(@RequestBody Customer customer){
       customer = customerService.addCustomer(customer);
       return customer;
       }
       
       @RequestMapping(value="/delete/{customerId}",method=RequestMethod.GET)
       public StatusDTO delete(@PathVariable("customerId") long customerId){
       
       customerService.deleteCustomer(customerId);
       StatusDTO status = new StatusDTO();
       status.setMessage("Customer Deleted Successfully");
       status.setStatus(200);
       return status;
       }
       
      }
  5. Create Customer DAO Layer
    • create applicationContext-jdbc.xml config
      • <?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:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
         xmlns:jee="http://www.springframework.org/schema/jee" 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
         http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
         http://www.springframework.org/schema/aop
         http://www.springframework.org/schema/aop/spring-aop-4.0.xsd">
         <context:annotation-config />
         <context:component-scan base-package="org.javasavvy.spring.services" />
         <context:component-scan base-package="org.javasavvy.spring.dao" />
         <tx:annotation-driven transaction-manager="transactionManager" />
        
         <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
         <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
         <property name="url" value="jdbc:mysql://localhost:3306/javasavvy" />
         <property name="username" value="root" />
         <property name="password" value="root" />
         </bean>
         <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
         <property name="entityManagerFactory" ref="entityManagerFactory" />
         </bean>
         <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
         <property name="dataSource" ref="dataSource" />
         <property name="persistenceUnitName" value="spring-jpa-unit" />
         <property name="jpaVendorAdapter"> 
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
         </property>
         <property name="jpaProperties">
         <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
         <prop key="hibernate.format_sql">false</prop>
         <prop key="hibernate.hbm2ddl.auto">update</prop>
         </props>
         </property>
         </bean>
        
         <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
        
        </beans>
    • Create Customer Entity
      • package org.javasavvy.spring.entity;
        
        
        import java.util.Date;
        
        import javax.persistence.Entity;
        import javax.persistence.GeneratedValue;
        import javax.persistence.GenerationType;
        import javax.persistence.Id;
        import javax.persistence.Table;
        import javax.persistence.Temporal;
        import javax.persistence.TemporalType;
        
        @Entity
        @Table(name="customer")
        public class Customer {
         
         @Id
         @GeneratedValue(strategy=GenerationType.AUTO)
         private long customerId;
         private String customerName;
         
         
         private String country;
         
         @Temporal(TemporalType.TIMESTAMP)
         private Date createdDate;
         
         @Temporal(TemporalType.TIMESTAMP)
         private Date updateDate;
        
         public Date getUpdateDate() {
         return updateDate;
         }
        
         public void setUpdateDate(Date updateDate) {
         this.updateDate = updateDate;
         }
        
         public long getCustomerId() {
         return customerId;
         }
        
         public void setCustomerId(long customerId) {
         this.customerId = customerId;
         }
        
         public String getCustomerName() {
         return customerName;
         }
        
         public void setCustomerName(String customerName) {
         this.customerName = customerName;
         }
        
         public String getCountry() {
         return country;
         }
        
         public void setCountry(String country) {
         this.country = country;
         }
        
         public Date getCreatedDate() {
         return createdDate;
         }
        
         public void setCreatedDate(Date createdDate) {
         this.createdDate = createdDate;
         }
        
         
        }
    • Create persistence.xml file
      • <?xml version="1.0" encoding="UTF-8"?>
        <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
         <persistence-unit name="spring-jpa-unit">
         </persistence-unit>
        </persistence>
    • Create Customer DAO Interface
      • package org.javasavvy.spring.dao;
        
        import java.util.List;
        
        import org.javasavvy.spring.entity.Customer;
        
        public interface CustomerDAO {
         
         public Customer addCustomer(Customer customer);
         public Customer updateCustomer(Customer customer);
         public void deleteCustomer(long customerId);
         public Customer getCustomer(long customerId);
         public List<Customer> getCustomers();
        
        }
    • Create Customer DAO Impl class
      • package org.javasavvy.spring.dao;
        
        import java.util.List;
        
        import javax.persistence.EntityManager;
        import javax.persistence.PersistenceContext;
        
        import org.javasavvy.spring.entity.Customer;
        import org.springframework.stereotype.Repository;
        import org.springframework.transaction.annotation.Transactional;
        
        @Repository("customerDAO")
        @Transactional
        public class CustomerDAOImpl implements CustomerDAO{
         
         
         @PersistenceContext
         public EntityManager entityManager;
        
         @Transactional(readOnly=false)
         public Customer addCustomer(Customer customer) {
         
         entityManager.persist(customer);
         return customer;
         }
        
         @Transactional(readOnly=false)
         public Customer updateCustomer(Customer customer) {
         entityManager.merge(customer);
         return customer;
         }
        
         @Transactional(readOnly=false)
         public void deleteCustomer(long customerId) {
         
         Customer cusomer = getCustomer(customerId);
         entityManager.remove(cusomer);
         }
        
         @Transactional(readOnly=true)
         public Customer getCustomer(long customerId) {
         String sql = "select customer from Customer customer where customer.customerId="+customerId;
         try{
         return (Customer) entityManager.createQuery(sql).getSingleResult();
         }catch(Exception e){
         }
         return null;
         }
        
         @Transactional(readOnly=true)
         public List<Customer> getCustomers() {
         
         return entityManager.createQuery("select customer from Customer customer").getResultList();
         }
        
        }
  6. Create Customer Service Layer
    • Create Customer Service Interface
      • package org.javasavvy.spring.services;
        
        import java.util.List;
        
        import org.javasavvy.spring.entity.Customer;
        
        public interface CustomerService {
         
         public Customer addCustomer(Customer customer);
         public Customer updateCustomer(Customer customer);
         public Customer getCustomer(long customerId);
         public List<Customer> getAllCustomers();
         public void deleteCustomer(long customerId);
        }
    • Create Customer Service Impl class
      • package org.javasavvy.spring.services;
        
        import java.util.List;
        
        import org.javasavvy.spring.dao.CustomerDAO;
        import org.javasavvy.spring.entity.Customer;
        import org.springframework.beans.factory.annotation.Autowired;
        import org.springframework.beans.factory.annotation.Qualifier;
        import org.springframework.stereotype.Service;
        import org.springframework.transaction.annotation.Transactional;
        
        @Service("customerService")
        @Transactional
        public class CustomerServiceImpl implements CustomerService {
        
         @Autowired(required=true)
         @Qualifier("customerDAO")
         private CustomerDAO customerDAO;
         
         @Transactional
         public Customer addCustomer(Customer customer) {
         
         System.out.println("Cusomer Service create invoked:"+customer.getCustomerName());
         customer = customerDAO.addCustomer(customer);
         return customer;
         }
         @Transactional
         public Customer updateCustomer(Customer customer) {
         
         System.out.println("Cusomer Service Update invoked:"+customer.getCustomerName());
         customer = customerDAO.updateCustomer(customer);
         return customer;
         }
        
         public Customer getCustomer(long customerId) {
         return customerDAO.getCustomer(customerId);
         }
        
         public List<Customer> getAllCustomers() {
         return customerDAO.getCustomers();
         }
         @Transactional
         public void deleteCustomer(long customerId) {
         customerDAO.deleteCustomer(customerId);
         }
        
        
        }
  7. Now Deploy the changes to tomcat and access the below URL in REST client:
    • URL:http://localhost:8080/spring-rest-hibernate/rest/customer/add
    • {"customerId":0,"customerName":"google.com","country":"India",
       "createdDate":"2017-03-22","updateDate":"2017-03-22"}
  8. Access the all-customers URL like show below :http://localhost:8080/spring-rest-hibernate/rest/customer/allCustomer Spring REST tutorial

    Download Spring REST CRUD JPA Code

Leave a Comment

Your email address will not be published. Required fields are marked *