Spring Boot Web + Mybatis 员工管理单页面实现

Spring Boot 项目实践


  • 导入静态资源
    • 下载地址:https://www.kuangstudy.com/download 下的 SpringBoot 静态资源

在这里插入图片描述

  • 实体类
//部门
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Department {
    private Integer id;
    private String departmentName;
    private List<Employee> employees;
}
//员工
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Employee {
    private Integer id;
    private String employeeName;
    private String email;
    private Integer gender;
    private Date birthday;
    private Integer did;
    private Department department;
}

java 模拟数据库执行


  • mapper
    • 此处没有连接数据库,而是用代码模拟了数据达到相似效果
@Repository
public class DepartmentMapper {
    private static Map<Integer, Department> departmentMap=null;
    static {
        departmentMap=new HashMap<>();
        departmentMap.put(1,new Department(1,"美工"));
        departmentMap.put(2,new Department(2,"设计"));
        departmentMap.put(3,new Department(3,"前端"));
        departmentMap.put(4,new Department(4,"后端"));
        departmentMap.put(5,new Department(5,"测试"));
        departmentMap.put(6,new Department(6,"运维"));
    }
    //获取所有的部门信息
    public Collection<Department> getDepartment(){
        return departmentMap.values();
    }
    //获取指定的部门信息
    public Department getDepartmentById(Integer id){
        return departmentMap.get(id);
    }
}
@Repository
public class EmployeeMapper {
    private static Map<Integer, Employee> employeeMap=null;
    @Autowired
    private DepartmentMapper departmentMapper;
    static {
        employeeMap=new HashMap<>();
        employeeMap.put(1,new Employee(1,"小时","159784625@qq.com",1,new Date(),new Department(1,"美工")));
        employeeMap.put(2,new Employee(2,"小肖","159784882@qq.com",0,new Date(),new Department(2,"设计")));
        employeeMap.put(3,new Employee(3,"小范","159784625@qq.com",1,new Date(),new Department(3,"前端")));
        employeeMap.put(4,new Employee(4,"小磊","151378462@qq.com",1,new Date(),new Department(4,"后端")));
        employeeMap.put(5,new Employee(5,"小李","874564625@qq.com",1,new Date(),new Department(5,"测试")));
        employeeMap.put(6,new Employee(6,"小张","189784625@qq.com",1,new Date(),new Department(6,"运维")));
    }
    private static Integer uid=7;
    //添加员工
    void add(Employee employee){
        if (employee.getId()==null){
            employee.setId(uid++);
        }
        employee.setDepartment(departmentMapper.getDepartmentById(employee.getDepartment().getId()));
        employeeMap.put(employee.getId(),employee);
    }
    //删除员工
    public void delete(Integer id){
        employeeMap.remove(id);
    }
    //修改员工
    public void update(Employee employee){
        employeeMap.put(employee.getId(),employee);
    }
    //查看员工
    public Collection<Employee> get(){
        return employeeMap.values();
    }
    //根据id查询员工
    public Employee get(Integer id){
        return employeeMap.get(id);
    }
}

员工列表展示

  • html 页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<title>员工管理系统</title>
		<link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
		<link th:href="@{/css/dashboard.css}" rel="stylesheet">
	</head>
	<body>
    <!--顶部导航栏-->    
	<div th:replace="~{commons/commons::topbar}"></div>
		<div class="container-fluid">
			<div class="row">
                <!--侧边栏-->
				<div th:replace="~{commons/commons::sidebar(active='list')}"></div>
				<main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
					<h2>员工信息管理页面</h2>
					<div class="table-responsive">
						<table class="table table-striped table-sm">
							<thead>
								<tr>
									<th>id</th>
									<th>员工姓名</th>
									<th>邮件</th>
									<th>性别</th>
									<th>生日</th>
									<th>部门</th>
									<th>操作</th>
								</tr>
							</thead>
							<tbody>
								<tr th:each="employee:${employees}">
									<td th:text="${employee.getId()}"></td>
									<td th:text="${employee.getEmployeeName()}"></td>
									<td th:text="${employee.getEmail()}"></td>
									<td th:text="${employee.getGender()==0?'':''}"></td>
									<td th:text="${#dates.format(employee.getBirthday(),'yyyy-MM-dd')}"></td>
									<td th:text="${employee.department.getDepartmentName()}"></td>
									<td>
										<button class="btn btn-sm badge-primary">编辑</button>
										<button class="btn btn-sm badge-danger">删除</button>
									</td>
								</tr>
							</tbody>
						</table>
					</div>
				</main>
			</div>
		</div>
	</body>
</html>
  • Controller
@Controller
public class EmployeeController {
    @Autowired
    private EmployeeMapper employeeMapper;
    @RequestMapping("/list")
    public String list(Model model){
        Collection<Employee> employees = employeeMapper.get();
        model.addAttribute("employees",employees);
        return "employee/list";
    }
}

添加员工

  • html 页面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <title>员工管理系统</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/dashboard.css}" rel="stylesheet">
</head>

<body>
<!--顶部导航栏-->
<div th:replace="~{commons/commons::topbar}"></div>

<div class="container-fluid">
    <div class="row">

        <!--侧边栏-->
        <div th:replace="~{commons/commons::sidebar(active='list')}"></div>
        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
            <h2>添加员工页面</h2>
            <form th:action="@{/add}" method="post">
                <div class="form-group">
                    <label class="control-label">员工姓名</label><br/>
                    <div>
                        <input type="text" class="form-control" name="employeeName">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label">邮箱</label><br/>
                    <div>
                        <input type="email" class="form-control" name="email">
                    </div>
                </div>
                <div>
                    <label class="control-label">性别</label><br/>
                    <label class="radio-inline col-sm-1">
                        <input type="radio" name="gender" id="inlineRadio1" value="1" checked></label>
                    <label class="radio-inline">
                        <input type="radio" name="gender" id="inlineRadio2" value="0"></label>
                </div>
                <div class="form-group">
                    <label>部门</label>
                    <select class="form-control" name="department.id" >
                        <option th:each="department:${departments}" th:text="${department.getDepartmentName()}" th:value="${department.getId()}"></option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="control-label">员工生日</label><br/>
                    <div>
                        <input type="text" class="form-control" name="birthday">
                    </div>
                </div>
                <button type="submit" class="col-sm-1 btn btn-primary">添加</button>
            </form>
        </main>
    </div>
</div>

<!--放置在文档的末尾,以便页面加载速度更快-->
<script type="text/javascript" th:src="@{/js/jquery-3.2.1.slim.min.js}" ></script>
<script type="text/javascript" th:src="@{/js/popper.min.js}" ></script>
<script type="text/javascript" th:src="@{/js/bootstrap.min.js}" ></script>
</body>
</html>
  • Controller
  • url 相同,提交方式不同,看做两次不同请求
    • GetMapping 获得部门信息,并将信息带到添加页面
    • PostMapping 提交添加请求,执行添加方法
@GetMapping("/add")
public String toAdd(Model model){
    Collection<Department> departments = departmentMapper.getDepartment();
    model.addAttribute("departments",departments);
    return "employee/add";
}
@PostMapping("/add")
public String Add(Employee employee){
    employeeMapper.add(employee);
    return "redirect:/list";
}

修改员工

  • html
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">

<head>
    <title>员工管理系统</title>
    <link th:href="@{/css/bootstrap.min.css}" rel="stylesheet">
    <link th:href="@{/css/dashboard.css}" rel="stylesheet">
</head>

<body>
<!--顶部导航栏-->
<div th:replace="~{commons/commons::topbar}"></div>

<div class="container-fluid">
    <div class="row">

        <!--侧边栏-->
        <div th:replace="~{commons/commons::sidebar(active='list')}"></div>
        <main role="main" class="col-md-9 ml-sm-auto col-lg-10 pt-3 px-4">
            <h2>修改员工页面</h2>
            <form th:action="@{/update}" method="post">
                <input name="id" th:value="${employee.getId()}" type="hidden">
                <div class="form-group">
                    <label class="control-label">员工姓名</label><br/>
                    <div>
                        <input type="text" class="form-control" name="employeeName" th:value="${employee.getEmployeeName()}">
                    </div>
                </div>
                <div class="form-group">
                    <label class="control-label">邮箱</label><br/>
                    <div>
                        <input type="email" class="form-control" name="email" th:value="${employee.getEmail()}">
                    </div>
                </div>
                <div>
                    <label class="control-label">性别</label><br/>
                    <label class="radio-inline col-sm-1">
                        <input type="radio" name="gender" id="inlineRadio1" value="1" th:checked="${employee.getGender()==1}"></label>
                    <label class="radio-inline">
                        <input type="radio" name="gender" id="inlineRadio2" value="0" th:checked="${employee.getGender()==0}"></label>
                </div>
                <div class="form-group">
                    <label>部门</label>
                    <select class="form-control" name="department.id">
                        <option th:selected="${department.getId()==employee.getDepartment().getId()}" th:each="department:${departments}" th:text="${department.getDepartmentName()}" th:value="${department.getId()}"></option>
                    </select>
                </div>
                <div class="form-group">
                    <label class="control-label">员工生日</label><br/>
                    <div>
                        <input type="text" class="form-control" name="birthday" th:value="${#dates.format(employee.getBirthday(),'yyyy-MM-dd')}">
                    </div>
                </div>
                <button type="submit" class="col-sm-1 btn btn-primary">修改</button>
            </form>
        </main>
    </div>
</div>

<!--放置在文档的末尾,以便页面加载速度更快-->
<script type="text/javascript" th:src="@{/js/jquery-3.2.1.slim.min.js}" ></script>
<script type="text/javascript" th:src="@{/js/popper.min.js}" ></script>
<script type="text/javascript" th:src="@{/js/bootstrap.min.js}" ></script>
</body>
</html>
  • Controller
@GetMapping("/update")
public String toUpdate(Model model,int id){
    Employee employee = employeeMapper.get(id);
    Collection<Department> departments = departmentMapper.getDepartment();
    model.addAttribute("employee",employee);
    model.addAttribute("departments",departments);
    return "employee/update";
}
@PostMapping("/update")
public String toUpdate(Employee employee){
    employeeMapper.update(employee);
    return "redirect:/list";
}

删除员工

  • html
<a class="btn btn-sm badge-danger" th:href="@{/delete(id=${employee.getId()})}">删除</a>
  • Controller
@RequestMapping("/delete")
public String delete(int id){
    employeeMapper.delete(id);
    return "redirect:/list";
}

Spring Boot 与 Mybatis 整合项目


  • 创建 springboot 时,勾选 Mybatis 相关的依赖

在这里插入图片描述

  • 在 pom.xml 中导入依赖
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.1</version>
    <scope>compile</scope>
</dependency>
  • 编写数据源和 Mybatis 的配置
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true
    driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
  mapper-locations: classpath:mybatis/mapper/*.xml
  type-aliases-package: com.yqly.pojo
  • EmployeeMapper
@Mapper
@Repository
public interface EmployeeMapper {
    //查询
    List<Employee> queryEmployee();
    //根据id查询员工
    Employee queryEmployeeById(Integer id);
    //添加员工
    int addEmployee(Employee employee);
    //删除员工
    @Delete("delete from mybatis.employee where id=#{id}")
    int deleteEmployee(@Param("id") Integer id);
    //修改员工
    int updateEmployee(Employee employee);
}
  • DepartmentMapper
@Mapper
@Repository
public interface DepartmentMapper {
    //查看部门信息
    @Select("select * from mybatis.department")
    List<Department> queryDepartment();
    //查看部门
    @Select("select * from mybatis.department where id=#{id}")
    Department queryDepartmentById(@Param("id") Integer id);
}
  • EmployeeMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.yqly.mapper.EmployeeMapper">
    <resultMap id="employeede" type="employee">
        <result column="id" property="id"/>
        <result column="employeeName" property="employeeName"/>
        <result column="email" property="email"/>
        <result column="gender" property="gender"/>
        <result column="birthday" property="birthday"/>
        <association property="department" javaType="department">
            <result column="id" property="id"/>
            <result column="departmentName" property="departmentName"/>
        </association>
    </resultMap>
    <select id="queryEmployee" resultMap="employeede">
        select e.id,e.employeeName,e.email,e.gender,e.birthday,e.did,d.id,d.departmentName
        from mybatis.employee e,mybatis.department d
        where e.did=d.id;
    </select>
    <select id="queryEmployeeById" resultMap="employeede" parameterType="int">
        select e.id,e.employeeName,e.email,e.gender,e.birthday,e.did,d.id,d.departmentName
        from mybatis.employee e,mybatis.department d
        where e.did=d.id and e.id=#{id};
    </select>
    <insert id="addEmployee" parameterType="employee">
        insert into mybatis.employee(employeeName, email, gender, birthday, did)
        values (#{employeeName},#{email},#{gender},#{birthday},#{did})
    </insert>
    <update id="updateEmployee" parameterType="employee">
        update mybatis.employee
        <set>
            <if test="employeeName!=null">
                employeeName=#{employeeName},
            </if>
            <if test="email!=null">
                email=#{email},
            </if>
            <if test="gender!=null">
                gender=#{gender},
            </if>
            <if test="birthday!=null">
                birthday=#{birthday},
            </if>
            <if test="did!=null">
                did=#{did}
            </if>
        </set>
        where id=#{id};
    </update>
</mapper>
  • application.yaml
spring:
  #配置数据源
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8&useSSL=true
    driver-class-name: com.mysql.cj.jdbc.Driver
  #绑定i18n配置文件  
  messages:
    basename: i18n.login
  #自定义时间格式
  mvc:
    format:
      date: yyyy-MM-dd
#mybatis配置文件
mybatis:
  type-aliases-package: com.yqly.pojo
  mapper-locations: classpath:mybatis/mapper/*.xml

完整代码资源链接:https://download.csdn.net/download/qq_46003863/78271586

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值