zoukankan      html  css  js  c++  java
  • Mybatis(个人学习总结)

    Mybatis总结

    1.什么是Mybatis?(官网文档copy的)

    • Mybatis就是一个简化JDBC的一个方便使用的框架(优秀的持久层框架)。
    • MyBatis 避免了几乎所有的 JDBC代码和手动设置参数以及获取结果集。
    • 它支持定制化 SQL、存储过程以及高级映射。
    • 可以通过XML和注解来配置和映射原生类型、接口和 Java 的 POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。
    • MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。
    • 2013年11月迁移到Github。

    2.如何获取并且使用Mybatis?

    • 获取Mybatis依赖:
      可以去Maven的中央仓库,复制中央仓库当中的Mybatis依赖的地址
    • 导入Mybatis依赖:
      在Maven项目中的pom.xml导入依赖,想导入别的依赖的方式相同

    3.配置Mybatis
    1.配置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核心配置文件-->
    <configuration>
        <properties resource="db.properties"/>
        <!--日志-->
        <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
            <!--开启sql字段转化为驼峰命名-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
        </settings>
        <!--起别名-->
        <typeAliases>
            <typeAlias type="com.sqx.pojo.User" alias="user"/>
            <typeAlias type="com.sqx.pojo.Student" alias="student"/>
        </typeAliases>
    
        <!--环境-->
        <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="com/sqx/dao/UserMapper.xml"/>
            <mapper resource="com/sqx/dao/StudentMapper.xml"/>
        </mappers>
    
    </configuration>```
    

    2.其中的数据库信息可以通过引入文件的方式获取(为了解耦合)所以编写db.properties

    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/book?useSSL=true&;useUnicode=true;characterEncoding=UTF-8
    username:
    password:
    

    3.配置2个文件完成后,编写工具类MybatisUtils来获取sqlsession(封装着对数据库操作的一切方法)
    底层原理:
    sqlSessionFactoryBuilder读取编写的配置文件,生成sqlSessionFactory
    (工厂制造机器,生成一个针对于该数据库的一个工厂)
    sqlSessionFactory生产SqlSession(封装着对于该数据库操作的一切方法)

    package com.sqx.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 {
            try {
                //获取SqlSessionFactory对象(相当于一个工厂产出SqlSession(产品))
                String resource = "mybatis-config.xml";
                InputStream inputStream= Resources.getResourceAsStream(resource);
                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
        //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。
        // SqlSession 提供了在数据库执行 SQL 命令所需的所有方法
        //此时设置了事务的自动提交,不需要手动commit
        public static SqlSession getSqlSession(){
            return  sqlSessionFactory.openSession(true);
        }
    
    }
    
    

    4,然后就是编写Dao层的Mapper接口
    接口中是对数据库中的一些操作的方法

    public interface StudentMapper {
        //添加一条学生信息
        int add(Student student);
        //通过id删除一条学生信息
        int deleteById(@Param("sid") Integer id);
        //修改某个学生的学生信息
        int update(Student student);
        //查询某个学生通过id
        Student queryById(@Param("sid") Integer id);
        //查询所有信息
        List<Student> queryAll();
    }
    
    

    4.接下来就是重点了
    为每个方法绑定sql语句(两种方法)
    方法一:通过xml配置文件
    为对应的Mapper接口绑定一个同名的xml文件
    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.sqx.dao.StudentMapper">
        <insert id="add" parameterType="student">
            insert into book.stu_info(sid,sno, sname, sex, age, email)
            values (null ,#{sno},#{sname},#{sex},#{age},#{email});
        </insert>
        <delete id="deleteById" parameterType="int">
            delete from book.stu_info where sid =#{sid};
        </delete>
        <update id="update" parameterType="student">
            update book.stu_info set sno=#{sno},sname=#{sname},sex=#{sex},age=#{age},email=#{email}
            where sid =#{sid};
        </update>
        <select id="queryById" parameterType="int" resultType="student">
            select * from book.stu_info where sid=#{sid};
        </select>
        <select id="queryAll" resultType="student">
            select * from book.stu_info;
        </select>
    </mapper>
    

    注意点:
    传参问题:

    • 如果传入多个参数可以使用Map集合来处理, Map<K,V>其中key是关键字,value是要传入的值
      sql语句可以通过传入的key拿到对应的Value值
    • 传入为一般数据类型就直接拿就可以
    • 传入的参数如果为属性也可以直接拿

    返回值问题:

    • 如果返回值是一般类型那么就直接resultType=返回类型即可
    • 如果返回值是集合返回类型是集合当中存储数据的类型

    字段不一致问题:

    • sql查询语句出来的字段与接受其数据的对象属性不一致的时候可以采用sql起别名也可以采用resultMap来进行映射字段 同时映射字段也是存在两种方式(可以处理一对多和多对一关系的问题):
    • sql起别名(简单但是太low)
    • 多对一:多个学生关联一个老师,
      在数据库当中他们是以外键的形式连接
      在pojo层的实体类当中Student类中有一个Teaacher类的属性
    
        <!--方式1,采取嵌套查询-->
        <select id="queryStudents"  resultMap="TeacherStudent">
             select * from mybatis.student;
        </select>
        <resultMap id="TeacherStudent" type="Student">
            <result property="id" column="id"/>
            <result property="name" column="name"/>
            <association property="teacher" column="tid" javaType="Teacher" select="queryTeachers"/>
        </resultMap>
    
        <select id="queryTeachers" resultType="Teacher">
            select * from mybatis.teacher where id =#{tid};
        </select>
    
    <!--方式2,采取结果嵌套-->
        <select id="queryStudents2" resultMap="resultStudent">
            SELECT
            s.`id` sid,
            s.`name` sname,
            t.`name` tname
            FROM student s,teacher t WHERE s.`tid`=t.`id`;
        </select>
        <resultMap id="resultStudent" type="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <association property="teacher" javaType="Teacher">
                <result property="name" column="tname"/>
            </association>
        </resultMap>
    

    一对多:
    在数据库当中他们是以外键的形式连接
    在pojo层的实体类当中Teacher类中有一个Student集合的属性用来存放对应的对

    **方法二:通过注解

    public interface TeacherMapper {
    
        @Select("select * from teacher where id =#{id}")
        Teacher queryTeacherById(@Param("id") int id);
    }
    
  • 相关阅读:
    uniApp 实现微信小程序和app视频播放flv格式视频监控
    uniapp 给子组件传值不及时显示
    uni-app 中$refs 在app中无法使用
    使用甘特图
    背景图片加蒙版,里面内容不受影响
    MyBatis 多对一操作
    在Maven项目中使用lombok
    MyBatis使用分页
    Log4j打印日志
    paramiko 下载文件
  • 原文地址:https://www.cnblogs.com/qxsong/p/14321073.html
Copyright © 2011-2022 走看看