MyBatis框架的学习总结一

MyBatis 简介

  1. MyBatis 是一个 ORM 框架, 用于操作数据库, 底层是对 jdbc 进行的封装。
  2. MyBatis 的前身是 iBatis, 是 Apache 下的一个开源项目。
  3. 现在MyBatis 迁移到GitHub上了,API中文使用文档和以及MyBatis 各版本下载地址

MyBatis 环境搭建 jar 包详解

创建一个java工程后,导入从jar包

  1. 核心jar包

    • mybatis-3.2.7.jar 里面封装了io,jdbc,bulider等
  2. MyBatis 依赖的 jar

    • asm-3.3.1.jar 字节码解析包, 被 cglib 依赖
    • cglib-2.2.2.jar 动态代理的实现
    • commons-logging-1.1.1.jar 日志包 javassist-3.17.1-GA.jar 字节码解析包
    • log4j-1.2.17.jar 日志包
    • log4j-api-2.0-rc1.jar 日志
    • log4j-core-2.0-rc1.jar 日志
    • slf4j-api-1.7.5.jar 日志
    • slf4j-log4j12-1.7.5.jar 日志
  3. 驱动 jar

    • mysql-connector-java-5.1.48.jar mysql的驱动jar包
    • ojdbc6.jar oracle的驱动jar包

MyBatis 核心配置文件

  1. 要求

    是一个 xml 文件 ,命名无要求 , 位置无要求 ,一般叫 mybatis.xml或applicationContext-dao.xml,放在 src 目录下

  2. dtd

    MyBatis官方提供了dtd约束,方便编写

    <?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">
    
  3. 配置文件的内容

<?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>
  1. 解释下方标签的含义
  • <configuration>这是配置文件的根元素, 所有的其他元素都要在这个标签下使用.

  • <environments>用于管理所有的环境, 并可以指定默认使用哪个环境. 通过 default 属性来指定.

  • <environment>用于配置环境. id 属性用于唯一标识当前环境

  • <transactionManager>用于配置事务管理器

    • type属性用于指定 MyBatis 采用何种方式管理事务
      • JDBC: 表示 MyBatis 采用与原生 JDBC 一致的方式管理事务
      • MANAGED: 表示将事务管理交给其他容器进行, 例如 Spring
  • <DataSource>用于配置数据源, 设置 MyBatis 是否使用连接池技术, 并且配置数据库连接的四个参数

    • type 属性用于设置 MyBatis 是否使用连接池技术
      • POOLED, 表示采用连接池技术
      • UNPOOLED, 表示每次都会开启和关闭连接, 不使用连接池技术
      • JNDI, 使用其他容器(例如 Spring)提供数据源
  • <property>用于配置数据库连接参数(driver, url, username, password)

  • <mappers> 是需要写入映射文件的全路径,但是要以斜杠划分。

    <mapper resource="com/batis/mapper/UserMapper.xml"/>

  • <properties> 用于加载外部的 properties 文件。获取 properties 文件中数据时, 要通过${}的方式获取。

    <properties resource="db.properties"></properties>

  • <typeAlias> 用于给pojo类给取别名。

    <typeAlias type="com.batis.pojo.User" alias="User"></typeAlias>

  1. 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="org.mybatis.example.BlogMapper">
  <select id="selectBlog" parameterType="int" resultType="Blog">
    select * from Blog where id = #{id}
  </select>
</mapper>
  • mapper 根元素
  • namespace属性 用于指定命名空间, mybatis 是通过 namespace+id 的方式来定位 SQL 语句的, 所以必须指定 namespace. 通常 namespace 被配置为全限定路径。
  • select 用于定义查询语句(DQL)
  • id 属性 用于唯一表示 SQL 语句, 类似于方法的方法名。
  • resultType 属性 用于设定查询返回的数据类型, 要写类型的全限定路径. 如果返回的是集合类型, 要写集合的泛型的类型。

查询语句参数的传入

  1. 方法一

    首先在接口中定义方法,映射文件中提供对应的标签。 此时, SQL 语句中获取方式有两种,通过#{param+数字}和#{arg+数字}的方式。

    <select id="selectuser" resultType="User"><!--在核心配置文件中使用typeAlias,取了别名,这里直接用user-->
    select * from t_user2 where uname=#{arg0} and pwd = #{arg1}
    select * from t_user2 where uname=#{param1} and pwd = #{param2}
    </select>
    
  2. 方法二

    接口中定义方法,参数中使用@Param 注解设定参数名用于在 SQL 语句中使用。@Param后面是sql中使用的别名。映射文件中提供对应的标签。 SQL 语句中获取方式有两种, 通过#{参数名称}或#{param+数字}的方式。

  3. 参数个数的查询

    • 一个参数时,#{}中可以任意填写。

    • 多个参数的查询,多个参数传递时,由于 sqlSession 中提供的查询方法只允许传入一个参数,因此可以对多个参数进行封装,可以使用对象或 Map 集合。

      UserMapper mapper;
      public TestBatis() throws IOException {
      //加载mybatis的核心配置文件applicationContext-dao.xml,注意配置文件要放在src目录下
      Reader in = Resources.*getResourceAsReader("applicationContext-dao.xml");
      //通过配置文件构建工厂类
      SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
      //通过工厂类创建发送sql语句的session对象,默认事务的提交是手动的
      SqlSession session = factory.openSession();
      mapper = session.getMapper(UserMapper.class);
      	}
      }
      

      接口中

      public User selByMap(Map<String,String> map);
      

      映射文件中

      <select id="selByMap" resultType="User">
          select * from t_user2 where uname=#{name} and pwd = #{pwd}  <!--取map集合中的key的名字-->
      </select>
      

      测试程序代码:

      @Test
      public void selByMap(){
          //加载mybatis的核心配置文件applicationContext-dao.xml,注意配置文件要放在src目录下
          Reader in = Resources.getResourceAsReader("applicationContext-dao.xml");
          //通过配置文件构建工厂类
          SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(in);
          //通过工厂类创建发送sql语句的session对象,默认事务的提交是手动的
          SqlSession session = factory.openSession();
          UserMapper mapper = session.getMapper(UserMapper.class);
          Map<String,String> map = new HashMap<>();
          map.put("name","曹操"); //key的名字随便取
          map.put("pwd","123456");
          User user = mapper.selByMap(map);
          System.out.println(user);
          session.commit();//手动提交
          session.close();//关闭流
      }
      

inser新增语句

在mapper 文件中, 通过<insert>定义新增语句。注意, 由于 DML 操作的返回值都是 int 类型 , 所以 , 不需要定义 resultType 属性。

<insert id="adduser">
	insert into usertable values(seq_user_uid.nextval,#{uname},#{pwd},#{spower})
</insert>

删除语句

与上述insert语句类似,通过<delete>定义语句,同样不需要写resultType。

<delete>
	delete from t_user2 where uname = #{uname}
</delete>

修改语句

修改语句的情况比上述的新增,删除麻烦许多,如果你是每次修改都是将所有属性进行修改, 那就跟上述的新增的操作一样。可我要是只想修改某一个属性,而且想要修改属性的个数和种类不确定,这样的需求下,我们就使用动态的sql语句。

动态SQL语句

根据条件的不同, SQL 语句也会随之动态的改变。MyBatis 中,提供了一组标签用于实现动态 SQL。

  1. <if> 用于进行条件判断,test 属性用于指定判断条件。 为了拼接条件, 在 SQL 语句后强行添加 1=1 的恒成立条件。
<?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.batis.mapper.UserMapper">
    <select id="selBy" resultType="User">
        select * from t_user2 where 1=1
        <if test="uname != null and uname != ''">
            and uname = #{uname}
        </if>
        <if test="pwd !=null and pwd !=''">
            and pwd = #{pwd}
        </if>
        <if test="sid != 0">
            and sid = #{sid}
        </if>
    </select>
</mapper>
  1. <where> 如果没有条件,不会生成 where 关键字,如果符合条件, 会自动添加 where 关键字,多个条件符合时会添加and。
<select id="selBy2" resultType="User">
    select * from t_user2
    <where>   <!--如果后面if中有一个成立,会自动加上where,如果都不成立,忽略where-->
        <if test="uname != null and uname != ''">
            and uname = #{uname}
        </if>
        <if test="pwd !=null and pwd !=''">
            and pwd = #{pwd}s
        </if>
        <if test="sid != 0">
            and sid = #{sid}
        </if>
    </where>
</select>
  1. <choose><when><otherwise>就跟switch...case...差不多,符合哪种条件就拼接哪种条件。
<select id="">
	<where>
​		<choose>
​				<when test="条件1"> 
​				</when>
​				<when test="条件2"> 
​				</when>
​			<otherwise>
​		</otherwise>
​	</choose>
</where>
</select>
  1. <set>用于维护 update 语句中的 set 子句,可以解决修改属性个数和种类不确定的问题,功能如下:
    • 满足条件时, 会自动添加 set 关键字。
    • 会去除 set 子句中多余的逗号。
    • 不满足条件时, 不会生成 set 关键字。
<update id="">
​		<set>
​		<if test="条件1">
​		</if>
​		<if test="条件2"> 
​		</if>
​		</set>
</update>
  1. <bind>用于对数据进行再加工,用于模糊查询。
<select id="selLike" resultType="User">
    <bind name="uname" value="'%'+uname+'%'"/>
    select * from t_user2 where uname like #{uname}
</select>
  1. <foreach>用于在 SQL 语句中遍历集合参数,在 in 查询中使用
<foreach collection="" open="" separator="" close="" item=""></foreach>
  • collection: 待遍历的集合。
  • open: 设置开始符号。
  • separator: 项目分隔符。
  • close: 设置结束符号。
  • item: 迭代变量。

接口中代码:public List<User> findIn(List<Integer> list);

<select id="findIn" resultType="User">
    select * from t_user2 where sid in
    <foreach collection="list" open="(" separator="," close=")" item="i">
        #{i}
    </foreach>
</select>
  1. <sql><include><sql>用于提取 SQL 语句, <include>用于引用 SQL 语句。
<sql id="">
​  列名1,列名2,列名3,...
​</sql>
<select id="" resultType="">
​  select 
​<include refid=*"**列名**2**"*/>
 from ...
</select>
posted @ 2021-03-29 15:32  念笙  阅读(156)  评论(0)    收藏  举报