Spring MVC с MySQL и Junit — поиск сотрудников по местоположению

Опубликовано: 9 Января, 2023

В реальных сценариях организации существуют в разных местах. Сотрудники доступны во многих местах. Иногда они работают в двух разных местах, т. е. в течение нескольких дней они работают в месте 1, а еще несколько дней они работают в месте 2. Давайте смоделируем этот сценарий с помощью запросов MySQL и подготовим приложение Spring MVC, которое взаимодействует с MySQL, и получим необходимые детали. А также давайте посмотрим тестовые примеры JUNIT.

Требуемые запросы MySQL:

DROP DATABASE IF EXISTS test;

CREATE DATABASE test;

USE test;

DROP TABLE test.employeesdetails;

CREATE TABLE `employeesdetails` (
  `id` int(6) unsigned NOT NULL,
  `Name` varchar(50) DEFAULT NULL,
  `AvailableDays` varchar(200) DEFAULT NULL,
  `location` varchar(50) DEFAULT NULL,
  `qualification` varchar(20) DEFAULT NULL,
  `experience` int(11) DEFAULT NULL,
  `gender` varchar(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(1,"EmployeeA","Monday,Tuesday,Friday","Location1","BE",5,"Female");

INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(2,"EmployeeB","Monday,Wednesday,Friday","Location1","MCA",3,"Female");

INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(3,"EmployeeC", "Wednesday,Thursday","Location2","BE",5,"Female");

INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(4,"EmployeeD","Saturday,Sunday","Location2","MBA",4,"Male");

INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(5,"EmployeeE","Tuesday,Thursday","Location2","MCA",3,"Female");

INSERT INTO `test`.`employeesdetails`
(`id`,`Name`,`AvailableDays`,`location`,`qualification`,
`experience`,`gender`) VALUES
(6,"EmployeeA","Wednesday,Thursday","Location2","BE",5,"Female");

SELECT * FROM test.employeesdetails;

Вывод test.employeedetails:

С этой настройкой давайте запустим проект Spring MVC, который взаимодействует с MySQL, и создадим детали по нашим запросам.

Реализация

Структура проекта:

Это проект, управляемый Maven. Давайте начнем с

пом.xml

XML




<?xml version="1.0" encoding="UTF-8"?>
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.employees</groupId>
   <artifactId>SpringMVCFindEmployee</artifactId>
   <packaging>war</packaging>
   <version>0.0.1-SNAPSHOT</version>
   <name>SpringMVCFindEmployee Maven Webapp</name>
   <url>http://maven.apache.org</url>
   <properties>
      <failOnMissingWebXml>false</failOnMissingWebXml>
      <spring-version>5.1.0.RELEASE</spring-version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>4.12</version>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.mockito</groupId>
         <artifactId>mockito-all</artifactId>
         <version>1.9.5</version>
         <scope>test</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-webmvc</artifactId>
         <version>${spring-version}</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${spring-version}</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-test</artifactId>
         <version>${spring-version}</version>
      </dependency>
      <dependency>
         <groupId>org.apache.tomcat</groupId>
         <artifactId>tomcat-jasper</artifactId>
         <version>9.0.12</version>
      </dependency>
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>javax.servlet-api</artifactId>
         <version>3.1.0</version>
         <scope>provided</scope>
      </dependency>
      <dependency>
         <groupId>javax.servlet</groupId>
         <artifactId>jstl</artifactId>
         <version>1.2</version>
      </dependency>
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>8.0.11</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>${spring-version}</version>
      </dependency>
   </dependencies>
   <build>
      <finalName>SpringMVCFindEmployee</finalName>
      <sourceDirectory>src/main/java</sourceDirectory>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5.1</version>
            <configuration>
               <source>1.8</source>
               <target>1.8</target>
            </configuration>
         </plugin>
         <!-- This should be added to overcome Could not initialize
               class org.apache.maven.plugin.war.util.WebappStructureSerializer -->
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-war-plugin</artifactId>
            <version>3.3.2</version>
         </plugin>
      </plugins>
   </build>
</project>

Давайте посмотрим на некоторые важные java-файлы.

Класс бобов

Сотрудник.java

Java




public class Employee {
    // All instance variables should
      // match with the columns present
      // in MySQL test.employeedetails table
    private int id;
    private String name;
    private float salary;
    private String availableDays;
    private String location;
    private String qualification;
    private int experience;
    private String gender;
    public String getLocation() {
        return location;
    }
 
    public void setLocation(String location) {
        this.location = location;
    }
 
    public String getQualification() {
        return qualification;
    }
 
    public void setQualification(String qualification) {
        this.qualification = qualification;
    }
 
    public int getExperience() {
        return experience;
    }
 
    public void setExperience(int experience) {
        this.experience = experience;
    }
 
    public String getGender() {
        return gender;
    }
 
    public void setGender(String gender) {
        this.gender = gender;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public float getSalary() {
        return salary;
    }
 
    public void setSalary(float salary) {
        this.salary = salary;
    }
 
    public String getAvailableDays() {
        return availableDays;
    }
 
    public void setAvailableDays(String availableDays) {
        this.availableDays = availableDays;
    }
 
}

СотрудникКонтроллер.java

Java




import com.employees.beans.Employee;
import com.employees.dao.EmployeeDao;
import java.sql.SQLException;
import java.util.StringTokenizer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
 
@Controller
@SessionAttributes("employee")
public class EmployeeController {
    @Autowired
    EmployeeDao dao;
 
    @Autowired public EmployeeController(EmployeeDao dao)
    {
        this.dao = dao;
    }
 
    @ModelAttribute("employee")
    public Employee getEmployee()
    {
        return new Employee();
    }
 
    // for searchform
    @RequestMapping("/employeesearchform")
    public String searchform(Model m)
    {
        m.addAttribute("command", new Employee());
        return "employeesearchform";
    }
 
    // It provides search of employees in model object
    @RequestMapping(value = "/searchEmployee",
                    method = RequestMethod.POST)
    public ModelAndView
    searchEmployee(@ModelAttribute("employee")
                   Employee employee)
    {
 
        ModelAndView mav = null;
        Employee employee1;
        try {
            employee1 = dao.getEmployeesByNameAndLocation(
                employee.getName(), employee.getLocation());
            mav = new ModelAndView("welcome");
            if (null != employee1) {
                System.out.println(
                    employee1.getId() + "..."
                    + employee1.getName() + ".."
                    + employee1.getAvailableDays()
                    + "..chosen location.."
                    + employee.getLocation());
                StringTokenizer st = new StringTokenizer(
                    employee1.getAvailableDays(), ",");
                boolean isAvailable = false;
                while (st.hasMoreTokens()) {
                    // System.out.println(st.nextToken());
                    // if
                    // (st.nextToken().equalsIgnoreCase(employee.getAvailableDays()))
                    // {
                    isAvailable = true;
                    break;
                    //}
                }
 
                mav.addObject("firstname",
                              employee1.getName());
                if (isAvailable) {
                    mav.addObject("availability",
                                  "Available on");
                }
                else {
                    mav.addObject("availability",
                                  "Not Available on");
                }
                mav.addObject("day",
                              employee1.getAvailableDays());