从零记录搭建一个干净的mybatis环境

文章目录

      • 1.新建一个空白项目
      • 2.清理及配置pom.xml
        • [2.1 删除src文件夹](#2.1 删除src文件夹)
        • [2.2 修改pom.xml](#2.2 修改pom.xml)
      • 3.新建module工程
        • [3.1 新建项目](#3.1 新建项目)
        • [3.2 删除webapp文件夹](#3.2 删除webapp文件夹)
        • [3.3 清理pom.xml](#3.3 清理pom.xml)
        • 3.4.连接mysql数据库
      • 4.构建mybatis增删改查内容
        • [4.1 写好resources目录下的内容](#4.1 写好resources目录下的内容)
        • [4.2 构建工具类](#4.2 构建工具类)
        • [4.3 创建Student和Teacher实体类](#4.3 创建Student和Teacher实体类)
        • [4.4 编写实体类对应的mapper接口](#4.4 编写实体类对应的mapper接口)
        • [4.5 编写Mapper接口对应的Mapper.xml文件](#4.5 编写Mapper接口对应的Mapper.xml文件)
        • [4.6 给StudentMapper接口增加方法以及编写对应xml文件](#4.6 给StudentMapper接口增加方法以及编写对应xml文件)
        • 4.7顶层mapper文件注册该mapper
        • [4.8 测试](#4.8 测试)

1.新建一个空白项目

FIle-->New-->Project

注意选择maven项目,项目命名,jdk选择, Archetype选择如下

2.清理及配置pom.xml

2.1 删除src文件夹

如果不在该项目下新建多个module不需要此操作

2.2 修改pom.xml

将资源文件复制到 target 目录,以便在项目的打包或运行时能够访问这些配置文件

供复制代码

java 复制代码
  <build>
    <resources>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>true</filtering>
      </resource>
    </resources>
  </build>

增加依赖

xml 复制代码
<!--父工程-->
  <dependencies>
    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>
    <!--junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
    </dependency>

  </dependencies>

3.新建module工程

3.1 新建项目
3.2 删除webapp文件夹
3.3 清理pom.xml
3.4.连接mysql数据库



数据库连接成功

4.构建mybatis增删改查内容

4.1 写好resources目录下的内容

mybatis-config.xml内容如下

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>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&amp;useUnicode=false&amp;characterEncoding=UTF-8&amp;serverTimezone=UTC"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

如下图

4.2 构建工具类

作用:提供了一个 SqlSession 对象,用于执行数据库操作并管理数据库连接

代码供复制

java 复制代码
package com.aloha.utils;

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 MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;
    static {
        String resource = "mybatis-config.xml";
        try {
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession() {
        return sqlSessionFactory.openSession();
    }
}
4.3 创建Student和Teacher实体类

和你数据库表一一对应

Teacher:

java 复制代码
package com.aloha.pojo;

import lombok.Data;

@Data // getter and setter 有参无参构造 toString
public class Teacher {
    private int id;
    private String name;
}

Student

java 复制代码
package com.aloha.pojo;

import lombok.Data;

@Data
public class Student {
    private int id;
    private String name;
    // 多个学生可以是同一个老师,多对一
    private Teacher teacher;
}
4.4 编写实体类对应的mapper接口

dao下编写两个interface

StudentMapper, TeacherMapper
StudentMapper

4.5 编写Mapper接口对应的Mapper.xml文件

StudentMapper.xml

java 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aloha.dao.StudentMapper">

</mapper>

TeacherMapper.xml

java 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aloha.dao.TeacherMapper">

</mapper>
4.6 给StudentMapper接口增加方法以及编写对应xml文件
java 复制代码
package com.aloha.dao;

import com.aloha.pojo.Student;

import java.util.List;

public interface StudentMapper {
    // 获取所有学生及其老师信息
    public List<Student> getStudents();
}
xml 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aloha.dao.StudentMapper">
    <!--
    需求:获取所有学生及对应老师的信息
    思路:
        1. 获取所有学生的信息
        2. 根据获取的学生信息的老师ID->获取该老师的信息
        3. 思考问题,这样学生的结果集中应该包含老师,该如何处理呢,数据库中我们一般使用关联查询?
            1. 做一个结果集映射:StudentTeacher
            2. StudentTeacher结果集的类型为 Student
            3. 学生中老师的属性为teacher,对应数据库中为tid。
               多个 [1,...)学生关联一个老师=> 一对一,一对多
            4. 查看官网找到:association -- 一个复杂类型的关联;使用它来处理关联查询
-->
    <select id="getStudents" resultMap="StudentTeacher">
        select * from mybatis.student
    </select>
    <resultMap id="StudentTeacher" type="Student">
        <!--association关联属性  property属性名 javaType属性类型 column在多的一方的表中的列名-->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
    </resultMap>
    <!--
        这里传递过来的id,只有一个属性的时候,下面可以写任何值
        association中column多参数配置:
            column="{key=value,key=value}"
            其实就是键值对的形式,key是传给下个sql的取值名称,value是片段一中sql查询的字段名。
    -->
    <select id="getTeacher" resultType="teacher">
        select * from mybatis.teacher where id = #{id}
    </select>

</mapper>
4.7顶层mapper文件注册该mapper
xml 复制代码
<mappers>
        <mapper resource="com/aloha/dao/StudentMapper.xml"/>
    </mappers>
4.8 测试

src同级别目录下新建test文件,java/com.aloha.dao如下

代码供复制

java 复制代码
package com.aloha.dao;

import com.aloha.pojo.Student;
import com.aloha.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

public class StudentMapperTest {
    @Test
    public void test1() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        for (Student student : mapper.getStudents()) {
            System.out.println(student);
        }

        sqlSession.close();

    }
}

测试成功,环境搭建完成

相关推荐
lpfasd123几秒前
《21世纪金融资本论:投机资本的新理论》精读导引笔记
人工智能·笔记·金融
2501_941805937 分钟前
面向高可用微服务体系的状态管理演进与多语言实现经验融合实践分享文章
java·大数据·分布式
Knight_AL14 分钟前
使用 Nginx 为内网 Java 服务实现 HTTPS
java·nginx·https
提笔忘字的帝国15 分钟前
【2026版】macOS 使用 Homebrew 快速安装 Java 21 教程
java·开发语言·macos
抹香鲸之海20 分钟前
Easyexcel 多级横向合并表头
java·开发语言·windows
烟沙九洲24 分钟前
JVM 堆内存分代
java·jvm
less is more_093024 分钟前
文献学习——计及分时电价的电缆配电网多时段二阶段有功与无功协调快速鲁棒优化调度方法
笔记·学习·算法
BD_Marathon24 分钟前
SpringMVC——bean加载控制
java·开发语言·数据库
im_AMBER30 分钟前
Leetcode 97 移除链表元素
c++·笔记·学习·算法·leetcode·链表
悟空码字31 分钟前
SpringBoot + Redis分布式锁深度剖析,性能暴涨的秘密全在这里
java·spring boot·后端