Mybatis案例:员工管理系统

一、项目要求

现有一张员工表如下。利用本章所学知识完成一个员工管理系统。实现如下功能:根据id查询员工信息、新增员工信息、根据id修改员工信息、根据id删除员工信息。

在这里插入图片描述
要求:根据员工表在数据库中创建一个employee表,并利用本章所学知识完成一个员工管理系统,该系统需要实现以下几个功能。
(1)根据id查询员工信息;
(2)新增员工信息;
(3)根据id修改员工信息;
(4)根据id删除员工信息。

二、项目准备

软件:IntelliJ IDEA 2019.3.1
开发语言:JAVA
JDK: 1.8
所需包:
mysql-connector-java-5.1.47.jar
mybatis-3.4.6.jar
hamcrest-core-1.3.jar
junit-4.12-sources.jar

IDEA中创建项目及模块

以项目SZXM及其模块Mybatis-1创建为例。

  1. 创建项目SZXM后,删除src目录。
  2. 在项目SZXM创建模块Mybatis-1
    操作如下图
    在这里插入图片描述
  3. 构建模块的各类目录
    如:java源文件目录、资源文件目录、测试目录。
    (1)将src改成普通目录
    在这里插入图片描述
    (2)在src下创建如下目录结构(如:在src上创建子目录操作为src上右击鼠标 --> new --> directory)
    在这里插入图片描述
    (3)设置各目录的作用。
    main下的java子目录标记为图中的“Sources Root”,即为java源文件目录;
    main下的resources子目录图中的“Resources Root”,即为资源文件目录;
    test下的java子目录标记为图中的“Test Sources Root”,即为测试的源文件目录;
    一般有不成文规定文件存放位置:(下面包名中的lyrpx表示项目开发的公司名称,我这里用我的网名)
    com.lyrpx.pojo包:存入POJO类
    com.lyrpx.utils包:存放工具类
    com.lyrpx.mapper包:存放数据持久层接口、其实现类、映射文件(也有把映射文件放至resources的mapper文件夹中的作法)
    com.lyrpx.service包:存放业务类接口、其实现类

三、Mybaits项目实战

项目目标:
(1)根据id查询员工信息;
(2)新增员工信息;
(3)根据id修改员工信息;
(4)根据id删除员工信息。

第一步,按图手动导入相关JAR

(在maven项目中只要添加依赖,但此处我们要手动添加)
(1)单击File --> Project Structure…,弹出如下所示窗口,按步骤单击鼠标左键后导入全局库(要将mybatis、mysql、junit数据库三个JAR包导入)
在这里插入图片描述
你导入后如下图所示就OK了!
在这里插入图片描述
再到上述窗口的“Modules”选项下确定模块Mybatis-1有这些刚导入的包,就可以进入下一步了。

第二步,准备数据库及数据表

在Navicat创建数据库及数据表
(1)先启动Mysql
(2)打开Navicat
(3)按下图创建数据库
在这里插入图片描述
创建数据表及插入数据的脚本如下:

DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) NOT NULL,
  `age` int(11) NOT NULL,
  `position` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
INSERT INTO `employee` VALUES ('1', '张三', '20', '员工');
INSERT INTO `employee` VALUES ('2', '李四', '18', '员工');
INSERT INTO `employee` VALUES ('3', '王五', '35', '经理');

第三步、启动IDEA,按下述步骤配置数据库连接。

在这里插入图片描述

(3)弹出下图窗口,并做相关操作。

在这里插入图片描述
(4)测试连接
在这里插入图片描述
(5)连接成功后,单击上图的“Schemas"选择卡,刷新之后勾选你要求连接的数据库(可以选多个)。
在这里插入图片描述
(6)有下图的数据库及表,说明你成功了!
在这里插入图片描述

第四步,编写POJO类 – Employee

package com.lyrpx.pojo;

public class Employee {
    private int id;
    private  String name;
    private  int age;
    private  String position;

    public Employee() {
    }

    public Employee(int id, String name, int age, String position) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.position = position;
    }

    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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getPosition() {
        return position;
    }

    public void setPosition(String position) {
        this.position = position;
    }

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", position='" + position + '\'' +
                '}';
    }
}

第五步,编写mapper类----EmployeeMapper接口

package com.lyrpx.mapper;

import com.lyrpx.pojo.Employee;

import java.util.List;
public interface EmployeeMapper {
        //查询所有记录
        List<Employee> selectAll();
        //按id查询
        Employee selectById(int id);
        //添加记录
        int add(Employee employee);
        //按id修改记录
        int update(Employee employee);
        //按id删除记录
        int delete(int id);
}

第六步,创建属性文件db.properties(存放数据连接信息)

#配置数库连接信息
mysql.dirver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/szxm?useUnicode=true&characterEncoding=UTF-8
mysql.username=root
mysql.pwd=123456

第七步,创建mybatis的核心配置文件mybatis-config.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <!--引入属性文件:可以多个-->
    <properties resource="db.properties"/>
    <typeAliases>
        <package name="com.lyrpx.pojo"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${mysql.dirver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.pwd}"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

第八步,编写映射文件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.lyrpx.mapper.EmployeeMapper">
    <!--查询所有记录-->
    <select id="selectAll" resultType="Employee">
        select * from employee
    </select>
    <!--    按id查询-->
    <select id="selectById" resultType="Employee">
        select * from employee where id=#{id}
    </select>
    <!--添加-->
    <insert id="add" parameterType="com.lyrpx.pojo.Employee">
    insert into employee(id, name,age,position ) values (#{id},#{name},#{age},#{position})
</insert>
<!-- 修改-->
    <update id="update" parameterType="com.lyrpx.pojo.Employee">
        UPDATE employee
        <set>
            id=#{id},
            name =#{name},
            age=#{age},
            position =#{position}
        </set>
        <where>
            id = #{id}
        </where>
    </update>
    <!--    按id删除-->
    <delete id="delete">
        delete from employee where  id=#{id}
    </delete>
</mapper>

第九步,修改核心配置文件

配置中加载映射文件EmployeeMapper.xml。配置方法:在mybatis-config.xml的 元素后面加如下元素。

<mappers>
<mapper resource="mapper/EmployeeMapper.xml"/>
</mappers>

第十步,编写测试类MyTest

import com.lyrpx.mapper.EmployeeMapper;
import com.lyrpx.pojo.Employee;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

public class MyTest {
    //按id查询
    @Test
    public void test01() throws IOException {
//        第一步
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
//        第二步
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        //第3大步:调用接口对象的相应方法完成测试
        List<Employee> employee = mapper.selectAll();
        for (Employee employees : employee) {
            System.out.println(employees);
        }
//        按id查询
        System.out.println("=====================================");
        Employee employees = mapper.selectById(2);
        System.out.println(employees);
    }
    //新增员工信息
    @Test
    public void test02() throws IOException {
//        第一步
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
//        第二步
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        //第3大步:调用接口对象的相应方法完成测试
        //新增员工信息
        System.out.println("=====================================");
        Employee users = new Employee(4, "王六", 26, "扫地工");
        int n = mapper.add(users);
        if (n != 0) {
            System.out.println("成功");
        }
        sqlSession.commit();
        sqlSession.close();
    }
    // 按id修改
    @Test
    public void test03() throws IOException {
//        第一步
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
//        第二步
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        //第3大步:调用接口对象的相应方法完成测试
        // 按id修改
        Employee users = new Employee();
        users.setId(3);
        users.setName("易班");
        users.setAge(19);
        users.setPosition("总经理");
        int n = mapper.update(users);
        if (n != 0) {
            System.out.println("成功");

        }
        sqlSession.commit();
        sqlSession.close();
    }
    // 按id删除
    @Test
    public void test04() throws IOException {
//        第一步
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        SqlSession sqlSession = factory.openSession();
//        第二步
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        //第3大步:调用接口对象的相应方法完成测试
//        按id删除
        int result = mapper.delete(4);
        System.out.println(result);
        sqlSession.commit();
        sqlSession.close();

    }
}

四、源代码

源代码

  • 48
    点赞
  • 243
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TechLens

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值