Mybatis

官网使用教程:https://mybatis.net.cn/getting-started.html

官网使用教程:https://mybatis.net.cn/getting-started.html

IDEA相关插件:MybatisX

简单使用方式

要使用Mybatis首先需要从 XML 中构建 SqlSessionFactory

//mybatis核心xml配置文件
String resource = "org/mybatis/example/mybatis-config.xml";
//获取输入流,其中Resources来源于 org.apache.ibatis
InputStream inputStream = Resources.getResourceAsStream(resource);
通过xml创建sqlSessionFactory工厂类,工厂类用于获取SqlSession
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//获取SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
其中SqlSession有多种使用方式
第一种,使用namespace.id调用
List<Stu> list = sqlSession.selectList("fun.maluyao.mapper.StuMapper.getStu");
第二种,使用Mapper代理
StuMapper mapper = sqlSession.getMapper(StuMapper.class);
List<Stu> stu = mapper.getStu();
合并为一句:List<Stu> stu = sqlSession.getMapper(StuMapper.class).getStu();


释放资源:
SqlSession.close();

mapper代理的使用流程:

  1. 定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下 【一定要放在resource里面,不然找不到啊!】
  2. 设置SQL映射文件的namespace属性为Mapper接口全限定名
  3. 在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值 类型一致

好处:

  • 可以使用扫包的方式加载Mapper

    <mappers>
        <package name="fun.maluyao.mapper"/>
    </mappers>

使用带参数的Sql语句

public interface StuMapper {
    Stu getStuByNo(int no);
}
<select id="getStuByNo" resultType="fun.maluyao.module.Stu">
    select * from scores where no= #{no}
</select>

下面的标签用于起别名

<typeAliases>
    <typeAlias type="fun.maluyao.module.Stu" alias="stu"/>
</typeAliases>

这样就可以在resultType中起别名

<select id="getStu" resultType="stu">
        select no, name, subject, sex, score from scores;
    </select>

别名也可以加在包上

<typeAliases>
    <package name="fun.maluyao.module"/>
</typeAliases>
<select id="getStu" resultType="Stu">
    select no, name, subject, sex, score from scores;
</select>

数据库表的字段名称和实体类的属性名称不一致时不能自动封装数据

解决方案:

  1. Sql语句起别名,让不一样的字段别名和实体类的属性名称一样 缺点:每次查询都要起别名 解决方案:使用SQL片段

    <sql id="col">
    	no as no, name as name, subject as subject, sex as sex, score as score
    </sql>
    <select id="getStu" resultType="Stu">
    	select <include refid="col"/>  from scores;
    </select>

    缺点:不灵活

  2. resultMap:

    //id唯一表示,type:映射类型(支持别名)
    <resultMap id="mymap" type="fun.maluyao.module.Stu">
    //子标签 id:完成主键字段的映射 result:完成一般字段的映射
    //column:表的列名 property:实体的属性名
    	<result column="name" property="name"/>
    </resultMap>
    <select id="getStu" resultMap="mymap">
    	select *  from scores;
    </select>

    在mapper标签中使用resultMap属性替换掉resultType属性

Mybatis如何接收对应参数

Mybatis有两种占位符
	#{} 替换成?防止SQL注入
    ${}	字符串拼接,但是可以动态查询表名 列名(表名列名不固定的时候使用)
		select * from ${tableName};
前者为预编译SQL,后者是拼接SQL
parameterType用于设置参数类型,可以省略

特殊字符的处理

在xml中 小于号(<)算特殊字符
解决方式
	1.转义,&lt;
		select * from table where id &lt; #{id};
	2.CDATA区(输入CD快捷创建)
		<![CDATA[
            随便放字符,当作纯文本使用
        ]]>

多条件查询:

在mybatis中如何处理参数与占位符匹配
	1.散装,在参数前面加上@Param注解,注解值就是占位符名称
	2.把参数封装成对象传入,占位符会寻找调用对应get方法取对应的值(参数的占位符的名称要和传入对象的属性名称一致)
	3.封装成一个Map集合Map集合的键名称要和占位符名称保持一致

动态SQL(查询条件可能数量上是动态的,有的条件可以没有)

Mybatis对动态SQL有很强的支持

  • if
  • choose (when, otherwise)
  • trim (where , set)
  • foreach
if标签用于条件显示
	缺点:多条件and问题
	解决:1.使用恒等式1=1 2.使用<where>标签,他会自动去除第一个and
where标签:里面为空就会自己删除where,有条件去除开始的and

choose 标签:只保留一个条件

select * from scores
<choose><!--相当于switch-->
	<when test=" no!=null and no != '' "><!--相当于case-->
		no=#{no}
	</when>
	<when test="name!=null">
		name=#{name}
	</when>
</choose>

但是要是传入的一个条件都没有怎么办呢?加上otherwise标签就行了

select * from scores
<choose><!--相当于switch-->
	<when test=" no!=null and no != '' "><!--相当于case-->
		no=#{no}
	</when>
	<when test="name!=null">
		name=#{name}
	</when>
	<otherwise>
		1=1
	</otherwise>
</choose>

set标签和where标签一样,都是用于多个选项问题而出现的

<set>
            <if test="pop1!=null">
                col1=popp1,
            </if>
            <if test="pop2!=null">
                col2=popp2,
            </if>
        </set>

用于去除末尾,,内容为空时去除set

使用注解开发会比配置文件更加方便

  • @Select
  • @Updata
  • @Delete
  • @Insert

重要

注解完成简单功能(不能使用动态SQL)

配置文件完成复杂功能

使用MapKey注解可以输出一个map,注解的value对应map的key,value就是实体类

    @MapKey("no")
    Map<Integer,Main> selectByPrimaryKey(Integer id);

注意

注意,resultType仍然是实体类

<select id="selectByPrimaryKey" resultType="fun.maluyao.module.Main">

评论

评论加载中……