• Mybatis框架入门


    Mybatis的介绍

    Mybatis是一个操作数据库的框架。最开始叫做ibatis,从apache基金会脱离,加入googleCode正式更名为MyBatis。最终现在mybatis的代码托管在github

    这里写图片描述

    mybatis架构介绍

    mybatis架构

    1、 mybatis配置SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息。

    mapper.xml文件即sql映射文件,文件中配置了操作数据库的sql语句。此文件需要在SqlMapConfig.xml中加载。

    2、 通过mybatis环境等配置信息构造SqlSessionFactory即会话工厂

    3、 由会话工厂创建sqlSession即会话,操作数据库需要通过sqlSession进行。

    4、 mybatis底层自定义了Executor执行器接口操作数据库,Executor接口有两个实现,一个是基本执行器、一个是缓存执行器。

    5、 Mapped Statement也是mybatis一个底层封装对象,它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id。

    6、 Mapped Statement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至sql中,输入参数映射就是jdbc编程中对preparedStatement 设置参数

    7、 Mapped Statement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql后将输出结果映射至java对象中,输出结果映射过程相当于jdbc编程中对结果的解析处理过程。



    入门小demo

    • 依赖的jar包
    <dependencies>
        <!-- mysql -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>
    
        <!-- mybatis 包 -->
            <dependency>
                <groupId>org.mybatis</groupId>
                <artifactId>mybatis</artifactId>
                <version>3.2.7</version>
            </dependency>
      </dependencies>
    • 定义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>
        <!-- 连接数据库操作 -->
          <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://192.168.52.250:3306/mybatis?characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
              </dataSource>
            </environment>
          </environments>
          <!-- 加载对应的mapper文件 -->
              <mappers>
                <mapper resource="mapper.xml"/>
              </mappers>
    </configuration>
    
    • 定义mapper.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="test">
        <select id="selectBlog" resultType="Blog">
         select * from blog where id = #{id}
        </select>
    </mapper>
    
    • 测试代码
        public class MyBatisDemo1 {
            SqlSessionFactoryBuilder builder = null;
            SqlSessionFactory sqlSessionFactory = null;
            SqlSession sqlSession =  null;
    
            @Before
            public void init() throws IOException{
                 builder = new SqlSessionFactoryBuilder();
                //通过Reources来获取配置文件
                InputStream resourceAsStream = Resources.getResourceAsStream("SqlMapConfig.xml");
                 sqlSessionFactory = builder.build(resourceAsStream);
                 sqlSession = sqlSessionFactory.openSession();
            }
            @Test
            public void testMybatis() throws Exception {
                User selectOne = sqlSession.selectOne("selectBlog", 1);
                String username = selectOne.getUsername();
                System.out.println(username);
                //关闭sqlSession
                sqlSession.close();
            }
            @After
            public void after(){
                sqlSession.close();
            }
        }
    


    总结

    • parameterType和resultType
    parameterType:指定输入参数类型,mybatis通过ognl从输入对象中获取参数值拼接在sql中。
    resultType:指定输出结果类型,mybatis将sql查询结果的一行记录数据映射为resultType指定类型的对象。
    • #{}和${}
    #{}表示一个占位符号,通过#{}可以实现preparedStatement向占位符中设置值,自动进行java类型和jdbc类型转换,#{}可以有效防止sql注入。 #{}可以接收简单类型值或pojo属性值。 如果parameterType传输单个简单类型值,#{}括号中可以是value或其它名称。
    “%”#{name}”%”
    ${}表示拼接sql串,通过${}可以将parameterType 传入的内容拼接在sql中且不进行jdbc类型转换, ${}可以接收简单类型值或pojo属性值,如果parameterType传输单个简单类型值,${}括号中只能是value。
    • selectOne和selectList
    selectOne查询一条记录,如果使用selectOne查询多条记录则抛出异常:
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned by selectOne(), but found: 3
        at org.apache.ibatis.session.defaults.DefaultSqlSession.selectOne(DefaultSqlSession.java:70)
    
    selectList可以查询一条或多条记录。
    • resultMap

      resultType可以指定pojo将查询结果映射为pojo,但需要pojo的属性名和sql查询的列名一致方可映射成功。 
      如果sql查询字段名和pojo的属性名不一致,可以通过resultMap将字段名和属性名作一个对应关系 ,resultMap实质上还需要将查询结果映射到pojo对象中。

      resultMap可以实现将查询结果映射为复杂类型的pojo,比如在查询结果映射对象中包括pojo和list实现一对一查询和一对多查询。

    这里写图片描述

    id :此属性表示查询结果集的唯一标识,非常重要。如果是多个字段为复合唯一约束则定义多个id 。 
    Property:表示Orders类的属性。 
    Column:表示sql查询出来的字段名。 
    Column和property放在一块儿表示将sql查询出来的字段映射到指定的pojo类属性(set方法)上。 
    result:查询结果的普通列映射关系。


    自增主键返回

    <selectKey keyProperty="id" resultType="java.lang.Integer" order="AFTER">
                select last_insert_id();
    </selectKey>

     

  • 相关阅读:
    Ceph纠删码编码机制
    Vmware error:无法获得 VMCI 驱动程序的版本: 句柄无效。
    Virtual Box 安装过程(卸载Vmware后)
    解决安卓SDK更新dl-ssl.google.com无法连接的方法
    《中文核心期刊要目总览(2014年版)》——计算机、自动化类
    2014中国科技核心期刊(中国科技论文统计源期刊)名录——计算机类
    计算机专业方面的期刊
    Office 中的各种小tips(更新中)
    博客园添加背景音乐
    jmeter定时器
  • 原文地址:https://www.cnblogs.com/jifengblog/p/9221307.html
Copyright © 2020-2023  润新知