一份简单的 MyBatis Maven 工程

前言

借着工程实训的机会,将 MyBatis 框架回忆了一遍,在这里就整理一份基础的 MyBatis 文件,也算是一个记录吧,同时留待将来再用时备查。

这里的环境是:

  • IDEA 2021.1.2
  • jdk 1.8.0_291
  • MyBatis 3.5.7
  • MySQL 8.0.25

工程文件

1、文件结构

2、pom 配置文件

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.hust</groupId>
  <artifactId>mybatisdemo</artifactId>
  <version>1.0-SNAPSHOT</version>

  <name>mybatisdemo</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.25</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.7</version>
    </dependency>
  </dependencies>

  <build>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-jar-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
        <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
        <plugin>
          <artifactId>maven-site-plugin</artifactId>
          <version>3.7.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-project-info-reports-plugin</artifactId>
          <version>3.0.0</version>
        </plugin>
      </plugins>
    </pluginManagement>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.xml</include>
        </includes>
      </resource>
    </resources>
  </build>
</project>

这里要注意最后将 src/main/java 下的子包和孙子包等等这些包中的 xml 文件 include 一下。

3、resources 目录下的配置文件

db.properties 文件

driverName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/empdb?useSSL=true&useUnicode=true&autoReconnect=true&characterEncoding=utf-8&serverTimezone=GMT
userName=root
password=lf123456

这里要注意连接 MySQL 8 的数据库驱动的 JDBC 的包是 driverName=com.mysql.cj.jdbc.Driver

sqlmapconfig.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"></properties>
    <!--类的别名-->
    <typeAliases>
        <!--<typeAlias type="com.hust.pojo.Dept" alias="Dept"></typeAlias>-->
        <!--按照包名批量加载类-->
        <package name="com.hust.pojo"/>
    </typeAliases>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${driverName}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${userName}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <!--加载 mapper 文件-->
    <mappers>
        <!--<mapper resource="xxx/xxx.xml"></mapper>-->
        <!--按照包名批量加载 mapper 文件-->
        <package name="com.hust.dao"/>
    </mappers>
</configuration>

4、main 目录下的所有文件

DeptMapper.java 文件

package com.hust.dao;

import com.hust.pojo.Dept;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface DeptMapper {
    /**
     * 获取所有部门信息
     * @return
     */
    List<Dept>  getDeptList();

    /**
     * 根据部门编号获取部门信息
     * @param id
     * @return
     */
    Dept getDeptById(int id);

//    /**
//     * 增加部门
//     * 当参数超过 1 个的时候,需要添加注解
//     * @param dname
//     * @param loc
//     * @return
//     */
//    int addDept(@Param("dname") String dname, @Param("loc") String loc);

    /**
     * 增加部门
     * @param dept
     * @return
     */
    int addDept(Dept dept);

    /**
     * 修改部门所在的城市
     * @param id
     * @param loc
     * @return
     */
    int editDept(@Param("id") int id, @Param("loc") String loc);

    /**
     * 通过部门 id 删除部门信息
     * @param id
     * @return
     */
    int delDeptById(int id);
}

DeptMapper.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.hust.dao.DeptMapper">

    <resultMap id="deptMap" type="Dept">
        <id property="deptno" column="deptno"></id>
        <result property="name" column="dname"></result>
        <result property="loc" column="loc"></result>
    </resultMap>

    <!--获取所有部门信息,id 要和接口中的方法名一致-->
    <select id="getDeptList" resultMap="deptMap">
        SELECT * FROM dept;
    </select>

    <!--根据部门编号获取部门信息-->
    <select id="getDeptById" resultMap="deptMap">
        SELECT * FROM dept WHERE deptno=#{id};
    </select>

    <!--增加部门-->
    <insert id="addDept">
        INSERT INTO dept VALUES(null,#{name },#{loc});
    </insert>

    <!--修改部门所在的城市-->
    <update id="editDept">
        UPDATE dept SET loc=#{loc} WHERE deptno=#{id};
    </update>

    <!--通过部门 id 删除部门信息-->
    <delete id="delDeptById">
        DELETE FROM dept WHERE deptno=#{id};
    </delete>
</mapper>

Dept.java 文件

package com.hust.pojo;

/**
 * 部门实体类
 */
public class Dept {
    private int deptno;
    private String name;
    private String loc;

    public Dept() {
    }

    public Dept(int deptno, String name, String loc) {
        this.deptno = deptno;
        this.name = name;
        this.loc = loc;
    }

    public int getDeptno() {
        return deptno;
    }

    public void setDeptno(int deptno) {
        this.deptno = deptno;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getLoc() {
        return loc;
    }

    public void setLoc(String loc) {
        this.loc = loc;
    }
}

App.java 文件

package com.hust;

import com.hust.dao.DeptMapper;
import com.hust.pojo.Dept;
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 java.io.IOException;
import java.io.InputStream;


public class App {
    public static void main(String[] args) throws IOException {
        // mybatis 的配置文件
        InputStream in = Resources.getResourceAsStream("sqlmapconfig.xml");
        // 创建 sqlSessionFactory 工厂
        SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
        // 获取 sqlSession 对象,相当于在 JDBC 中封装好的 getConnection()
        SqlSession sqlSession = factory.openSession();
        DeptMapper deptMapper = sqlSession.getMapper(DeptMapper.class);

        /*List<Dept> list = deptMapper.getDeptList();
        for (Dept dept : list) {
            System.out.println(dept.getDname()); // 注意,后面为了演示,将 dname 属性名更改成了 name
        }*/

        /*Dept dept = deptMapper.getDeptById(10);
        if (dept != null) {
            System.out.println(dept.getDeptno() + ":" + dept.getName() + ":" + dept.getLoc());
        } else {
            System.out.println("无此部门");
        }*/

        /*Dept dept = new Dept();
        dept.setName("财务部");
        dept.setLoc("北京");
        int res = deptMapper.addDept(dept);
        if (res > 0) {
            System.out.println("部门添加成功");
        } else {
            System.out.println("添加失败");
        }*/

        /*int res = deptMapper.editDept(73, "宜昌");

        if (res == 1) {
            System.out.println("部门修改成功");
        } else {
            System.out.println("修改失败");
        }*/

        int res = deptMapper.delDeptById(73);

        if (res > 0) {
            System.out.println("部门删除成功");
        } else {
            System.out.println("删除失败");
        }

        sqlSession.commit(); // 修改数据库中的内容需要提交
        sqlSession.close(); // 关闭资源
    }
}

一份简单的 MyBatis Maven 工程
http://fanyfull.github.io/2021/06/23/一份简单的-MyBatis-Maven-工程/
作者
Fany Full
发布于
2021年6月23日
许可协议