Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Repository class using spring-mvc

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 484
    Comment on it

    Repository class using spring-mvc:

    As we know that Spring Framework is famous for it's loose coupling architecture. Spring provides a annotation called @Repository, it marks the class, and tells container that this class will be used as a Repository class. This Repository class is used only to do database related operations. Repository class decouples the database related code from the business logic. So Repository class deals with the back-end operations and also handles the database related exceptions with more informative information.

    Repository Class With Mysql DB : As the title describes, we use mysql database to store the records. You can choose any database to store your data, you just need to put that database's related jar to your application's lib. We are using Spring JdbcTemplate class to manage database related operations. Spring JdbcTemplate class handles the common operations like opening, closing the database connection and also handles the other database related resources.

    To use jdbc or Spring JDBC you need following jars in your project lib:

    1. spring-core.xxx.jar
    2. spring-context.xx.jar
    3. spring-aop.xxx.jar
    4. spring-jdbc.xxx.jar
    5. mysql-connector-java-5.0.5.jar

      OR

    you can use the following POM.XML -

    <dependencies>
            <dependency>
                   <groupId>junit</groupId>
                   <artifactId>junit</artifactId>
                   <version>3.8.1</version>
                   <scope>test</scope>
             </dependency>
             <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-orm</artifactId>
                    <version>3.2.0.RELEASE</version>
             </dependency>
              <dependency>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-webmvc</artifactId>
                    <version>3.2.0.RELEASE</version>
               </dependency>
               <dependency>
                    <groupId>jstl</groupId>
                    <artifactId>jstl</artifactId>
                    <version>1.2</version>
                </dependency>
                <dependency>
                     <groupId>org.springframework</groupId>
                     <artifactId>spring-context</artifactId>
                      <version>4.0.2.RELEASE</version>
                 </dependency>
                 <dependency>
                      <groupId>org.springframework</groupId>
                      <artifactId>spring-tx</artifactId>
                      <version>4.0.2.RELEASE</version>
                 </dependency>
                 <dependency>
                       <groupId>org.springframework</groupId>
                       <artifactId>spring-jdbc</artifactId>
                       <version>4.0.2.RELEASE</version>
                  </dependency>                     
                  <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>5.0.5</version>
                   </dependency>
        </dependencies>
    

    Example of Spring MVC and MySql :

    Create a model : Customer.java

    package com.evon.model;
    import org.springframework.data.annotation.Id;
    import org.springframework.data.mongodb.core.mapping.Document;
    
    public class Customer {
    
        private String id;
        private String name;
    
        public String getId() {
            return id;
        }
        public void setId(String id) {
            this.id = id;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
    }
    

    DAO Interface : CustomerDAO.java

    package com.evon.service;
    import java.util.List;
    import com.evon.model.Customer;
    
    public interface CustomerDAO {
        public void addCustomer(Customer customer);
        public List<Customer> listCustomer();
        public void deleteCustomer(Customer customer);
        public void updateCustomer(Customer customer);
    }
    

    Implementation of DAO : CustomerDAOImpl.java

    package com.evon.service;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Random;
    import java.util.UUID;
    import javax.sql.DataSource;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;
    import org.springframework.stereotype.Repository;
    import com.evon.model.Customer;
    
    @Repository
    public class CustomerDAOImpl implements CustomerDAO{
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        public void setDataSource(DataSource dataSource) {
            this.jdbcTemplate = new JdbcTemplate(dataSource);
        }
    
        public void addCustomer(Customer customer) {
            Random randomGenerator = new Random();
            int randomInt = randomGenerator.nextInt(100);
            String query="insert into Customer values('"+randomInt+"','"+customer.getName()+"')";  
            jdbcTemplate.update(query);  
            System.out.println("Customer record inserted successfully with id :"+customer.getId());
        }
    
        public List<Customer> listCustomer() {
            List<Customer> customerList = new ArrayList<Customer>();
            customerList = this.jdbcTemplate.query("select id,name from Customer", new RowMapper<Customer>() {
                public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Customer customer = new Customer();
                    customer.setId(rs.getString("id"));
                    customer.setName(rs.getString("name"));
                    return customer;
                }
            });
            return customerList;
        }
    
        public void deleteCustomer(Customer customer) {
            String SQL = "delete from Customer where id = ?";
            jdbcTemplate.update( SQL, new Object[]{customer.getId()} );
            System.out.println("Customer deleted successfully with id :"+customer.getId());
        }
    
        public void updateCustomer(Customer customer) {
            String SQL = "update Customer set name=? where id = ?";
            jdbcTemplate.update( SQL, new Object[]{customer.getName(), customer.getId()} );
            System.out.println("Customer updated successfully with id :"+customer.getId());
        }
    
        // map the db row to customer model object
        private class CustomerMapper implements RowMapper<Customer> {
           public Customer mapRow(ResultSet rs, int rowNum) throws SQLException {
              Customer customer = new Customer();
              customer.setId(rs.getString("id"));
              customer.setName(rs.getString("name"));
              return customer;
           }
        }
    }
    

    CustomerController.java

    package com.evon.controller;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.util.StringUtils;
    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.servlet.View;
    import org.springframework.web.servlet.view.RedirectView;
    import com.evon.model.Customer;
    import com.evon.service.CustomerDAO;
    
    @Controller    
    public class CustomerController {  
    
        @Autowired
        private CustomerDAO customerDao;
    
        @RequestMapping(value = "/customer", method = RequestMethod.GET)  
        public String getCustomerList(ModelMap model) {  
            model.addAttribute("customerList", customerDao.listCustomer());  
            return "output";  
        }  
    
        @RequestMapping(value = "/customer/save", method = RequestMethod.POST)  
        public View createCustomer(@ModelAttribute Customer customer, ModelMap model) {
            if(StringUtils.hasText(customer.getId())) {
                customerDao.updateCustomer(customer);
            } else {
                customerDao.addCustomer(customer);
            }
            return new RedirectView("/spring-mongodb/customer");  
        }
    
        @RequestMapping(value = "/customer/delete", method = RequestMethod.GET)  
        public View deleteCustomer(@ModelAttribute Customer customer, ModelMap model) {  
            customerDao.deleteCustomer(customer);  
            return new RedirectView("/spring-mongodb/customer");  
        }    
    }
    

    index.jsp

    <html>
    <body>
        <h2>Welcome to Home Page.</h2>
        <p>
            <a href="customer">Click here</a> to Register Customer.
        </p>
    </body>
    </html>
    

    WEB-INF/jsp/output.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <html>
    <body>
        <h2>Here is a simple CRUD using Spring MVC</h2>
    
            <form action="customer/save" method="post">
                <input type="hidden" name="id">
                <label for="name">Customer Name</label>
                <input type="text" id="name" name="name"/>
                <input type="submit" value="Submit"/>
            </form>
    
        <table border="1">
            <tr>
                <td>Id</td>
                <td>Name</td>
                <td>Action</td>
            </tr>       
            <c:forEach var="customer" items="${customerList}">
                <tr>
                    <td>${customer.id}</td>
                    <td>${customer.name}</td><td>
                    <input type="button" value="delete" onclick="window.location='customer/delete?id=${customer.id}'"/></td>
                </tr>
            </c:forEach>
        </table>    
    </body>
    </html>
    

    Configure the spring front controller: WEB-INF/Web.xml

    <web-app 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&#95;2_5.xsd"
            version="2.5">
    
      <display-name>Spring MVC Web Application with MySQL db</display-name>
    
        <servlet>
            <servlet-name>dispatcher</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <load-on-startup>1</load-on-startup>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>dispatcher</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <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>
    

    And spring configuration file : WEB-INF/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:p="http://www.springframework.org/schema/p"
           xsi:schemaLocation="
           http://www.springframework.org/schema/beans 
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/context 
           http://www.springframework.org/schema/context/spring-context-3.2.xsd">
    
        <context:component-scan base-package="com.evon.service" />
          <context:component-scan base-package="com.evon.controller" />
    
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <constructor-arg name="dataSource" ref="dataSource" />
        </bean> 
    
        <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/springTest" />
            <property name="username" value="root" />
            <property name="password" value="root" />
        </bean>    
    
           <bean id="jspViewResolver"
              class="org.springframework.web.servlet.view.InternalResourceViewResolver"
              p:prefix="/WEB-INF/jsp/"
              p:suffix=".jsp" />    
    </beans>
    

    Output : Screen 1 :

        home screen

    Screen-2

        screen-2

    When we fill the form and submit it, the Customer name will be saved into the database.

    Screen-3

        screen-3

    The customer list shown below the form is fetched from the database.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: