Mybatis-01-初识Mybatis

目录

帮助文档:https://mybatis.org/mybatis-3/zh/index.html

简介:

1.什么是MyBatis

2.Mybatis的优点:

1.简单易学:

2.灵活:

3.解除SQL与程序代码的耦合:

4.提供xml标签,

3.Mybatis是一个半自动化的ORM框架

1.使用Mybatis的步骤

1.引入mybatis的包,mysql驱动的jar包

引入静态文件

2.创建响应的实体类接口xml文件等

2.1.1.mybatis-config.xml

2.1.2.db.properties

2.2.until.Mybatis

2.3.mapper

2.3.1.mapper.StudentMapper

2.3.2.mapper.StudentMapper.xml

 2.4.pojo

2.4.1pojo.Student

2.5.测试


帮助文档:https://mybatis.org/mybatis-3/zh/index.html

简介:

1.什么是MyBatis

  • MyBatis 是一款优秀的持久层(数据访问层)框架。

  • 它支持自定义 SQL、存储过程以及高级映射。

  • MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。

  • MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

  • MyBatis 本是apache的一个开源项目iBatis。

  • 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。

  • 2013年11月迁移到Github

2.Mybatis的优点:

1.简单易学:

本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件就可以了,易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。

2.灵活:

Mybatis不会对应用程序或者数据库的现有的设计强加任何影响,SQL写在xml里,便于统一管理和优化。通过SQL语句可以满足操作数据库的所有操作

3.解除SQL与程序代码的耦合:

通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。SQL和代码的分离,提高了可维护性。

4.提供xml标签,

支持编写动态SQL

3.Mybatis是一个半自动化的ORM框架

(Object Relationship Mapping)--->对象关系映射

经验:使用框架通用步骤:1,引入jar包  2.编写xml配置文件   3.编写java代码

1.使用Mybatis的步骤

1.引入mybatis的包,mysql驱动的jar包

//mybatis的jar包依赖
<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.6</version>
</dependency>

//mysql的jar包依赖
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.38</version>
</dependency>

//log4j的jar包
<!-- https://mvnrepository.com/artifact/log4j/log4j -->
    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>1.2.17</version>
    </dependency>

引入静态文件

如果你创建的是java项目需要提前引入静态文件    在<build>标签里面

<?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">
    <parent>
        <artifactId>05_18_Mbatis-01</artifactId>
        <groupId>com.lzy.javaweb</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>com.lzy.05_31</artifactId>

    <build>
        <!--加载xml静态资源-->
            <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>


</project>

2.创建响应的实体类接口xml文件等

包:mapper,pojp,until

一个接口,一个xml文件,一个实体类,一个Mbatis工具类

三个配置文件db.properties/log4j.properties/mybatis-config.xml


接下类让我们跟随官方帮助文档进行学习

2.1.1.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>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="${driver}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
  </mappers>
</configuration>

 自己写

涉及的知识点:

这个xml文件用于获取数据库连接实例的数据源(DataSource)以及决定事务作用域和控制方式的事务管理器(TransactionManager)

  • <properties resource="db.properties"/>标签:用属性标签可以外部引用文件
  • <mapper resource="com/lzy/mapper/StudentMapper.xml"/>标签:映射器,需要告诉 MyBatis 到哪里去找到SQL语句,使用相对于类路径的资源引用,或完全限定资源定位符(包括 file:/// 形式的 URL),或类名和包名等

<?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"/>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
<!--        注册StudentMapper.xml-->
        <mapper resource="com/lzy/mapper/StudentMapper.xml"/>
    </mappers>
</configuration>

2.1.2.db.properties

properties标签引用的文件

注意:文件里面一个空格都不能多

在jdbc里面不使用“&” 使用“&amp;”

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3308/wlyb?useSSL=true&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=1234

但我们初步创Mybatis.xml文档之后接下来我们开始创建class文件


2.2.until.Mybatis

这个文件是Mybatis的核心文件我们用这个文件来创建SqlSession
 1.通过mybatis-config.xml文件
     * 使用Resources.getResourceAsStream(resource)方法
     * org.apache.ibatis.io.Resources引包
     * 获取InputStream对象
 2.通过new SqlSessionFactoryBuilder().build(inputStream)
     * 创建SqlSessionFactory对象(创建一次之后不再使用)
 3.通过sqlSessionFactory.openSession()创建SqlSession

用于官方写的比较散这里就不表

package com.lzy.until;

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 Mybatis {
    private static SqlSessionFactory sqlSessionFactory=null;
    /**
     * 1.通过mybatis-config.xml文件
     * 使用Resources.getResourceAsStream(resource)方法
     * org.apache.ibatis.io.Resources引包
     * 获取InputStream对象
     * 2.通过new SqlSessionFactoryBuilder().build(inputStream)
     * 创建SqlSessionFactory对象(创建一次之后不再使用)
     * 3.通过sqlSessionFactory.openSession()创建SqlSession
     */

    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();
    }
}

2.3.mapper

2.3.1.mapper.StudentMapper

 创建学生表的Mapper类StudentMapper

该命名就可以直接映射到在命名空间中同名的映射器类,并将已映射的 select 语句匹配到对应名称、参数和返回类型的方法

用接口类 

注意:方法参数里面要使用一个参数,如果参数多的时候就使用map集合

package com.lzy.mapper;

import com.lzy.pojo.Student;

import java.util.ArrayList;

public interface StudentMapper {
    /**
     * 学生表的接口
     */

    //1.查询所有
    ArrayList<Student> getSelect();
}

2.3.2.mapper.StudentMapper.xml

 映射文件

  • <mapper namespace="org.mybatis.example.BlogMapper">标签:里面写对应的接口类,进行绑定(如果没有定义类别名,就写全限定名)
  •  <select id="selectBlog" resultType="Blog">
        select * from Blog where id = #{id}
      </select>
  • id:填写接口里面的方法名
  • resultType:填写返回类型
  • #{} :填写通过方法传过来值的名称

官方

<?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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>

自己写

<?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.lzy.mapper.StudentMapper">
<!--  注意;编写完Mapper.xml文件之后要在mybatis-config.xml文件里面注册-->
<!--  问题1.StudentMapper接口类能使用类别名么?-->
<!--答:不能
    因为org.apache.ibatis.binding.BindingException: Type interface com.lzy.mapper.StudentMapper is not known to the MapperRegistry.
    类型接口com.lzy.mapper.StudentMapper不是已知的MapperRegistry。-->
<!--  1.查询所有-->
<select id="getSelect" resultType="com.lzy.pojo.Student">
    SELECT * FROM `student`
  </select>

</mapper>

 2.4.pojo

2.4.1pojo.Student

数据库表里面对应的实体类,每个实体类都应该有一个对应实体类

注意:为了节约博客空间已经将无参有参、set/get/toString方法省略,实际应该写

package com.lzy.pojo;

import java.io.Serializable;

/**
 * 学生实体类
 * 将实体类序列化
 * Student implements Serializable
 * 继承接口 Serializable
 */
public class Student implements Serializable {
    private String studentNumber;
    private String studentName;
    private int studentPassword;
    private int studentAge;
    private String studentDepartment;
    private String teacherNumber;
    private Teacher teacher;
}

2.5.测试

编写测试类之后发现了一些问题,已经放在了里面,但是不能包含全部问题欢迎大家帮我补充

@Test
    public void test01(){
        //测试:学生表01查询所有
        /**
         * 1.通过Mybatis.getSqlSession()获取SqlSession
         * 2.使用获取SqlSession创建接口对象StudentMapper
         * 3.StudentMapper对象调用查询方法
         * 4.遍历集合
         */
        /**
         * 第一次运行:报错
         * java.lang.NullPointerException(一种空指针异常)
         * 原因Mybatis.java类里面sqlSessionFactory异常
         * 解决:将整个设成静态代码块并且将sqlSessionFactory赋为null
         * 第二次运行:报错
         * Caused by: org.apache.ibatis.exceptions.PersistenceException:
         * ### Error building SqlSession.
         * ### The error may exist in com/lzy/mapper/StudentMapper.xml
         * ### Cause: org.apache.ibatis.builder.BuilderException:
         * Error parsing SQL Mapper Configuration. Cause:
         * java.io.IOException: Could not find resource com/lzy/mapper/StudentMapper.xml
         * 告诉我问题出现在Mapper.xml文件里面。但是里代码没有错
         * 最后找到问题原因:因为我创建的是mavenjava项目所以要在pom.xml里面添加加载静态资源的代码
         */
        SqlSession sqlSession = Mybatis.getSqlSession();
        StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
        ArrayList<Student> list = studentMapper.getSelect();
        for (Student student : list) {
            System.out.println(student);
        }
    }

到现在为止初步使用Mybatis的框架,我们还需要更加细致的了解和学习

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值