【案例介绍】

员工编号(id)员工名称(name)员工年龄(age)员工职位(position)
1张三20员工
2李四18员工
3王五35经理

现有一员工表,要求根据员工表在数据库中创建一个employee表,根据所学知识完成一个员工管理系统,该系统需要实现以下几个功能。

(1)根据id查询员工信息。

(2)新增员工信息。

(3)根据id修改员工信息。

(4)根据id删除员工信息。

【案例实现】

1.数据准备:在MySQL中创建一个名称为mybatis的数据库

CREATE DATABASE mybatis;

在数据库中创建employee表

CREATE TABLE employee(
	id int primary key auto_increment,
	name varchar(20) not null,
	age int not null,
	position varchar(20)
);

并插入3条数据

INSERT INTO employee(id,name,age,position) VALUES(null,'张三',20,'员工'),(null,'李四',18,'员工'),(null,'王五',35,'经理');

2.引入相关依赖:在项目的pom.xml文件中导入MySQL驱动包、JUnit测试包、MyBatis的核心包等相关依赖。

<?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>org.xinhua</groupId>
    <artifactId>MyBatisTest</artifactId>
    <version>1.0-SNAPSHOT</version>
 
    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
 
    <dependencies>
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.11</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.28</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>compile</scope>
        </dependency>
    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
 
</project>

3.POJO类准备:创建持久化类Employee,并在类中声明id(编号)、name(姓名)、age(年龄)和position(职位)属性,以及属性对应的getter/setter方法。

package com.itheima.pojo;

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

    public void setId(Integer id)
    {
        this.id = id;
    }
    public void setName(String name)
    {
        this.name = name;
    }
    public void setAge(Integer age)
    {
        this.age = age;
    }
    public void setPosition(String position)
    {
        this.position = position;
    }

    public Integer getId()
    {
        return id;
    }
    public String getName()
    {
        return name;
    }
    public Integer getAge()
    {
        return age;
    }
    public String getPosition()
    {
        return position;
    }

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

4.创建映射文件EmployeeMapper.xml:该文件主要用于配置SQL语句和Java对象之间的映射 。

<?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.itheima.mapper.EmployeeMapper">

    <!--(1)根据id查询员工信息 -->
    <select id="select01" parameterType="Integer"
            resultType="com.itheima.pojo.Employee">
        select * from employee where id = #{id}
    </select>

    <!-- (2)新增员工信息 -->
    <insert id="insert02" parameterType="com.itheima.pojo.Employee">
        insert into employee(id,name,age,position)values (#{id},#{name},#{age},#{position})
    </insert>

    <!-- (3)根据id修改员工信息 -->
    <update id="update03" parameterType="com.itheima.pojo.Employee">
        update employee set name= #{name},age = #{age},position= #{position} where id = #{id}
    </update>

    <!-- (4)根据id删除员工信息 -->
    <delete id="delete04" parameterType="Integer">
        delete from employee where id=#{id}
    </delete>
</mapper>

5.创建数据库连接信息配置文件db.properties:在该文件中配置数据库连接的参数。

mysql.driver=com.mysql.cj.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&\
  characterEncoding=utf8&useUnicode=true&useSSL=false
mysql.username=root
mysql.password=root

6.创建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"/>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <!--数据库连接相关配置,db.properties文件中的内容-->
            <dataSource type="POOLED">
                <property name="driver" value="${mysql.driver}"/>
                <property name="url" value="${mysql.url}"/>
                <property name="username" value="${mysql.username}"/>
                <property name="password" value="${mysql.password}"/>
            </dataSource>
        </environment>
    </environments>

    <!--mapping文件路径配置,用于将EmployeeMapper.xml映射文件加载到程序中-->
    <mappers>
        <mapper resource="mappers/EmployeeMapper.xml"/>
    </mappers>

</configuration>

7.编写MyBatisUtils工具类:该类用于封装读取配置文件信息的代码。

package com.itheima.Utils;

import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class MyBatisUtils {
    private static SqlSessionFactory sqlSessionFactory = null;
    //初始化SQLSessionFactory类加载MyBatis的配置文件
    static {
        try {
            //使用MyBatis提供的Resources类加载MyBatis的配置文件
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            //构建SqlSessionFactory工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    public static SqlSession getSession(){
        //获取SqlSession对象的静态方法
        return sqlSessionFactory.openSession(true);
        //若传入true表示关闭事务控制,自动提交;false表示开启事务控制
    }
}

8.编写测试类

package com.itheima;
import com.itheima.pojo.Employee;
import com.itheima.Utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class MyBatisTest {
    //(1)根据id查询员工信息
    @Test
    public void select01() {
        //通过工具类获取SQLSession对象
        SqlSession sqlSession = MyBatisUtils.getSession();
        //创建Employee对象接收SQL语句的查询结果
        Employee employee01 = sqlSession.selectOne("select01",2);
        System.out.println(employee01);
        //关闭事务
        sqlSession.close();
    }
    //(2)新增员工信息
    @Test
    public void insert02() {
        SqlSession sqlSession = MyBatisUtils.getSession();
        //实例化Employee
        Employee employee = new Employee();
        employee.setId(4);
        employee.setName("赵六");
        employee.setAge(100);
        employee.setPosition("老板");
        //这里的insertID一定要与EmployeeMapper文件中的id对应,要一模一样
        sqlSession.insert("insert02",employee);
        System.out.println("添加成功!");
        sqlSession.close();
    }
    //(3)根据id修改员工信息
    @Test
    public void update03() {
        SqlSession sqlSession = MyBatisUtils.getSession();
        Employee employee = new Employee();
        employee.setId(3);
        employee.setName("陈二");
        employee.setAge(40);
        employee.setPosition("经理");
        sqlSession.insert("update03",employee);
        System.out.println("更新成功!");
        sqlSession.close();
    }
    //(4)根据id删除员工信息
    @Test
    public void delete04() {
        SqlSession sqlSession = MyBatisUtils.getSession();
        sqlSession.delete("delete04", 1);
        System.out.println("删除成功!");
        sqlSession.close();
    }
}

9.运行结果

更多推荐