SpringBoot CRUD MySQL Demo


Project Structure:

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.developer</groupId>
<artifactId>SpringMySQL</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>SpringMySQL</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-jasper</artifactId>
</dependency>

<!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>


</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

resources\application.properties

spring.mvc.view.prefix=/WEB-INF/jsp/
spring.mvc.view.suffix=.jsp

spring.datasource.url=jdbc:mysql://localhost:3306/java_db
spring.datasource.username=root
spring.datasource.password=
#spring.jpa.generate.ddl=true


com\developer\SpringMySQL\controllers\MainController.java
package com.developer.SpringMySQL.controllers;

import com.developer.SpringMySQL.models.AppUsers;
import com.developer.SpringMySQL.models.AppUsersRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Pukar on 6/25/2017.
 */
@Controller
public class MainController {
    @Autowired
    AppUsersRepo appDao;

    @RequestMapping("/")
    public ModelAndView doHome() {
        ModelAndView mv = new ModelAndView("index");
        mv.addObject("lists", appDao.findAll());
        mv.addObject("msg", "Add New Record");
        return mv;
    }

    @RequestMapping("/view/{id}")
    public ModelAndView doView(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView("view");
        mv.addObject("lists", appDao.findOne(id));
        return mv;
    }
    @RequestMapping("/edit/{id}")
    public ModelAndView doEdit(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView("edit");
        mv.addObject("lists", appDao.findOne(id));
        return mv;
    }

    @RequestMapping("/delete/{id}")
    public ModelAndView doDelete(@PathVariable("id") int id) {
        ModelAndView mv = new ModelAndView("redirect:/");
        appDao.delete(id);
        return mv;
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView doSave(@RequestParam("id") String id, @RequestParam("firstname") String firstName, @RequestParam("lastname") String lastname) {
        ModelAndView mv = new ModelAndView("redirect:/");
        AppUsers users;
        if (!id.isEmpty()) {
            users = (AppUsers) appDao.findOne(Integer.parseInt(id));
        } else {
            users = new AppUsers();
        }
        users.setFirstName(firstName);
        users.setLastName(lastname);
        appDao.save(users);
        return mv;
    }
}

models\AppUsers.java

package com.developer.SpringMySQL.models;

import javax.persistence.*;

/**
 * Created by Pukar on 6/25/2017.
 */
@Entity
@Table(name="appusers")
public class AppUsers {
    private static final long serialVersionUID = -3009157732242241606L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int id;

    @Column(name = "firstname")
    public String firstName;

    @Column(name="lastname")
    public String lastName;

    public AppUsers() {
    }

    public AppUsers(String firstName, String lastName) {
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
}

models\AppUsersRepo.java
package com.developer.SpringMySQL.models;

import org.springframework.data.repository.CrudRepository;

/**
 * Created by Pukar on 6/25/2017.
 */
public interface AppUsersRepo extends CrudRepository<AppUsers,Integer> {
}

SpringMySqlApplication.java

package com.developer.SpringMySQL;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringMySqlApplication {

public static void main(String[] args) {
SpringApplication.run(SpringMySqlApplication.class, args);
}
}

webapp\WEB-INF\jsp\index.jsp
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html>
   <head>
      <title>Spring Boot Example</title>
   </head>

   <body>
    <p>List Of Users</p>
      <c:forEach var = "list" items = "${lists}">
         <p>
         ${list.id} ${list.firstName} ${list.lastName}
         <a href="/view/${list.id}">View</a>
         <a href="/edit/${list.id}">Edit</a>
         <a href="/delete/${list.id}">Delete</a>
         </p>
      </c:forEach>
      <hr/>
      <p>${msg}</p>
      <form method="post" action="/save">

      <hr/>
        First Name : <input type="text" name="firstname"/>
        <hr/>
        Last Name : <input type="text" name="lastname"/>
        <hr/>
        <input type="submit" value="save" name="submit"/>
      </form>
   </body>
</html>

webapp\WEB-INF\jsp\view.jsp
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html>
   <head>
      <title>Spring Boot Example</title>
   </head>

   <body>
    <p>Detail Users</p>
    <p><b>Id: </b>${lists.id}</p>
    <p><b>First Name: </b>${lists.firstName}</p>
    <p><b>Last Name: </b>${lists.lastName}</p>
   </body>
</html>

webapp\WEB-INF\jsp\edit.jsp
<%@ taglib uri = "http://java.sun.com/jsp/jstl/core" prefix = "c" %>
<html>
   <head>
      <title>Spring Boot Example</title>
   </head>

   <body>
    <p>List Of Edit</p>
      <hr/>
      <form method="post" action="/save">
      Id : <input type="text" name="id" value="${lists.id}"/>
      <hr/>
        First Name : <input type="text" name="firstname" value="${lists.firstName}"/>
        <hr/>
        Last Name : <input type="text" name="lastname"value="${lists.lastName}"/>
        <hr/>
        <input type="submit" value="save" name="submit"/>
      </form>
   </body>
</html>

Create Table:

 CREATE TABLE `appusers` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(30) NOT NULL,
  `lastname` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1 |

Demo:

Share on Google Plus

About Ram Pukar

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment

0 comments:

Post a Comment