Mybatis新手入门保姆级!!!

本文详细介绍了Mybatis的基本概念、持久化原理以及为何选择Mybatis。通过实例演示了如何创建一个Mybatis项目,包括配置数据库连接、编写实体类、接口和Mapper文件,以及解决资源配置问题。最后,文章讨论了如何通过封装提高代码复用性和可维护性,展示了Mybatis简化数据库操作的优势。
摘要由CSDN通过智能技术生成

提示:写完文章后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

当你的能力还不足以撑起您的野心时,你就需要静下心来,好好学习


一、Mybatis是什么?

在这里插入图片描述

  • MyBatis 是一款优秀的持久层框架;
  • 它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

二、持久化

2.1.持久化是什么?

  • 持久化就是将数据保存到硬盘、网络云盘(例如百度云)、U盘等等永久保存的设备。这种将内存中的数据保存到关系型数据库``

2.2持久层

  • 持久层分为三层分别是如下:
  • Dao层,Service层,Controller层
  • 每个模块都有自己的工作,低耦合,好维护,

三、为什么要使用Mybatis?

  • JDBC太复杂,来用Mybatis简化
  • sql语句和代码分离,好维护,简单明了
  • 提供xml文件,支持编写动态sql
  • 提供映射标签,对象就可以和数据库字段进行关系映射了

四、写第一个Mybatis程序

1.创建一个普通maven项目,不需要添加web模板,目前用不到

2.在pom.xml中导入需要的依赖

<!--编码格式和jdk版本-->
  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

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


    <!--    mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.1</version>
    </dependency>

    <!--jdbc-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.9</version>
    </dependency>

3.建立一个mybatis.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/student?useUnicode=true&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>
</configuration>

4.编写实体类

package pojo;

//学生类
public class Student {

    private Integer id;         //id
    private String name;        //姓名
    private Integer age;        //年龄
    private String gender;      //性别

   //get/set方法省略
}

5.编写接口

package dao;

import pojo.Student;

import java.util.List;

public interface StudentDao {

    public List<Student> selectstudent();		//查询全部学生信息
}

6.建立StudentMapper.xml

  • 在Mybatis中,我们不需要去写实现类了,写繁琐的代码,
  • 现在我们需要建一个StudentMapper.xml文件,在这里面编写sql语句, 用来让对象和数据库字段来映射
<?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">
<!--namespace:绑定一个dao/mapper接口-->
<mapper namespace="dao.StudentDao">
    <!--id:方法名-->
    <!--resultType:返回类型-->
    <select id="selectstudent" resultType="pojo.Student">
        select * from student
    </select>
</mapper>

7.建立Mybatis.xml

  • 现在编写完StudentMapper.xml文件,程序是不知道他的存在的,这时候就需要我们映射了
  • 在刚才建得Mybatis.xml中添加如下代码
<!--每一个Mapper.xml都需要在Mybatis核心配置文件中注册-->
    <mappers>
        <mapper resource="dao/StudentMapper.xml"/>
    </mappers>

8.编写测试类,这里会有个小BUG

package controller;

import dao.StudentDao;
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 pojo.Student;
import util.MybatisUtils;

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

public class StudentText {


    public static void main(String[] args) throws IOException {
        SqlSession session = null;

       //mybatis全局配置文件
       String resource = "mybatis.xml";
        //加载 mybatis 全局配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //根据 sqlSessionFactory 产生 session
        session = sessionFactory.openSession();
		//根据方法的返回值返回
        String statement = "dao.StudentDao.selectstudent";
        List<Student> students = session.selectList(statement);
        //遍历对象
        for (Student student:students){
            System.out.println(student);
        }
        //一定要记得关闭session
        session.close();

    
    }
}

8.1.运行报错

Exception in thread "main" java.lang.ExceptionInInitializerError
	at controller.StudentText.main(StudentText.java:39)
Caused by: org.apache.ibatis.exceptions.PersistenceException: 
### Error building SqlSession.
### The error may exist in dao/StudentMapper.xml
### Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource dao/StudentMapper.xml
  • 报错的说的是找不到StudentMapper.xml文件,为什么会找不到呢,我们不是在Mybatis中映射了吗?

8.2.因为我们没有在Maven中配置Resources

8.3.Resources是干什么的?

功能:主要用于打包资源文件,默认情况下maven只打包src/main/resource下的资源,通过:
1、设置build_resources
2、使用build-helper-maven-plugin插件
3、使用maven-resources-plugin插件
都可以自定义要打包的资源

一般情况下,我们用到的资源文件(各种xml,properties,xsd文件)都放在src/main/resources下面,利用maven打包时,maven能把这些资源文件打包到相应的jar或者war里。

有时候,比如mybatis的mapper.xml文件,我们习惯把它和Mapper.java放在一起,都在src/main/java下面,这样利用maven打包时,就需要修改pom.xml文件,来吧mapper.xml文件一起打包进jar或者war里了,否则,这些文件不会被打包的。(maven认为src/main/java只是java的源代码路径)。

8.4.在pom.xml中配置如下代码

 <build>
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
    </plugins>
  </build>

再次运行就成功了

Student{id=1, name='张三', age=18, gender='男'}
Student{id=5, name='李四', age=19, gender='男'}
Student{id=6, name='王五', age=20, gender='男'}
Student{id=7, name='王美丽', age=21, gender='女'}

一定要注意哦

9.封装

  • ,以下代码我们很清楚的看到这几句是固定的,和jdbc连接数据库一样,所以为了减少代码量和重复代码,我们需要把它们封装起来
 SqlSession session = null;

        //mybatis全局配置文件
        String resource = "mybatis.xml";
        //加载 mybatis 全局配置文件
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //构建sqlSession的工厂
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //根据 sqlSessionFactory 产生 session
        session = sessionFactory.openSession();

9.1封装类

//SqlSessionFactory session
public class MybatisUtils {
     private static  SqlSessionFactory sqlSessionFactory;
    static {

        //mybatis全局配置文件
        String resource = "mybatis.xml";
        //加载 mybatis 全局配置文件
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream(resource);
            //构建sqlSession的工厂
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //既然有了SqlSessionFactory,顾名思义,我们就可以从中获得SqlSession 的实例。
    //SsqlSession 完全包含了面对数据库执行SQL命令所需的所有方法
    public static SqlSession getSqlSession(){
        return  sqlSessionFactory.openSession();
    }
}

9.2 第二种方式

 		//第一步:获得SqlSession对象,使用工具类
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        //方式一:getMapper
        //通过getMapper直接获取类
        StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
        //取到方法的返回值
        List<Student> students =  studentDao.selectstudent();
		//遍历对象
        for (Student student : students) {
            System.out.println(student);
        }
  • 推荐使用第二种方式
  • 现在你的代码不仅更清晰,更加类型安全,还不用担心可能出错的字符串字面值以及强制类型转换。
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值