Mybatis 学习总结

本文详细介绍了MyBatis的核心配置文件,包括环境配置、数据源设置。接着讲解了接口与XML配置文件的连接,如resultType和resultMap的使用。还探讨了MyBatis如何从接口获取参数,以及特殊SQL查询如模糊查询、批量操作的方法。此外,还涉及动态SQL的多种标签应用,如if、where、choose等,并提到了分布查询和分步查询的实现。最后,文章提及了一些常见问题和报错的检查点。
摘要由CSDN通过智能技术生成

目录

一、核心配置文件

二、接口和配置文件的连接

1、resultType

2、resultMap

 三、Mybatis从接口获取参数的方式

1、接口传递的参数是单个基本数据时

2、接口传递的参数是多个基本数据时

3、接口传递的参数是类对象时

4、@Param("name") 通过起别名的方式传递参数

四、特殊的SQL查询

1、模糊查询

2、批量添加

3、批量删除

4、获取自增主键

五、动态SQL

1、

2、

3、

4、choose、when、otherwise

5、foreach

6、

六、分布查询

1、映射类中有类实体

2、映射类内有集合

七、工具类

八、遇到的问题报错


一、核心配置文件

        

<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>
可以通过<environments>配置多个数据库文件,default配置默认的数据库信息,

perdataSource后的数据库信息可以创建properties文件来映射相关数据,通过${}方式引用映射数据,但需要在配置文件之前声名路径信息<properties>
<properties resource="jdbc.properties"/>

之后配置相关接口xml配置文件通过<mapper>或者<package>标签。

<mapper resource="EmpMaper/EmpMaper.xml"/>
        <!--        <package name=""/>-->
        </mappers>

二、接口和配置文件的连接

配置文件中通过<mapper>标签连接接口,namespace中输入接口文件所在的包地址

<mapper namespace="com.at.SpecialSqlMaper">

接口中的方法需要和xml配置文件绑定 ,只需要和SQL标签内的id绑定即可。 

  <delete id="delectUser">
        delete from user where mima in(${mima})
    </delete>
    <select id="getListUser" resultType="com.po.User">
        select *from ${userName}
    </select>

如果是<select>标签需要设置映(即方法的返回值)

1、resultType

如果接口返回值是类:填入类的包地址即可;如果接口返回值是集合:也是填入对应类的包地址即可。如果是基本数据类型:Mybatis已经做好了封装,直接填即可;其中类的属性需要和数据库中属性一致(无关大小写),否则映射会出现问题;

2、resultMap

自定义映射,解决映射类属性和数据库中属性不一致的问题。

映射对象为类实体(且对象属性中还有一个其他的类对象),有两种映射方法

(例子为联合查询)

1、全部直接自定义映射

 <resultMap id="字段名" type="com.po.Dept">
        <id column="数据库主键字段" property="类属性"></id>
        <result column="数据库字段" property="类属性"></result>
         <result column="数据库字段" property="类内对象.属性"></result>
        <result column="数据库字段" property="类内对象.属性"></result>
       

    </resultMap>
    
    <select id="接口方法名字" resultMap="字段名字">
        select * from dept
            left join emp
                on dept.dept_id=emp.deot_id
        where dept.dept_id=#{deptId}
    </select>

2、通过<collection>标签处理类对象中的类实体和集合

    

 <resultMap id="getDePtAndemop" type="com.po.Dept">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
        <collection property="类中的实体对象或集合名" ofType="类中的实体对象或集合对应的属性包名地址">
            <id column="联合查询另一张表的主键" property="属性"></id>
            <result column="数据库字段" property="属性"></result>
           
        </collection>

    </resultMap>

    <select id="getDeptIdByEemp" resultMap="getDePtAndemop">
        select * from dept
            left join emp
                on dept.dept_id=emp.deot_id
        where dept.dept_id=#{deptId}
    </select>

当映射类中有其他类对象和集合时候除了联合查询还可以使用分布步查询。

 三、Mybatis从接口获取参数的方式

其中有两种方式:  #{}和${};它们的区别是:#{}会自动添加 “” 号,而${} 需要主动添加“”;为了防止SQL注入问题一般提倡使用#{}。

1、接口传递的参数是单个基本数据时

  SQL中 #{}或${}中内容可以是任意数据。

2、接口传递的参数是多个基本数据时

 SQL中 #{}或${}中内容只能是arg0,arg1...param1,param2..

3、接口传递的参数是类对象时

对象只需要#{属性}。

4、@Param("name") 通过起别名的方式传递参数

@Param("name")是为基本数据起别名时#{name};@Param("name")是为类对象取的别名时

#{name.属性}。

当需要传递的参数为数组或者集合时候放到之后内容说明

四、特殊的SQL查询

1、模糊查询

  #{}和${}区别就是是否会自动添加字符串的问题

使用  "%"#{数据}"%"  方式

<select id="getUserBylike" resultType="com.po.User">
        select *
        from user
        where mima   like "%"#{mohu}"%"
    </select>

2、批量添加

即接口传递参数方式是集合或者数组

使用<foreach>标签映射
<insert id="insertEmpByChose" >
        insert into emp values
        <foreach collection="参数名" item="自定义单个数据名" separator=",">
            (null,#{自定义单个数据名.属性},#{自定义单个数据名.属性},null)
        </foreach>
    </insert>

其中collection为对应@Param("")中内容;item为单个数据;separator为自定义分隔符。

3、批量删除

SQL可以使用in 等关键字实现

<delete id="DeletEmpByChoseOns">
        delete from emp where emp_id in(
            <foreach collection="参数名字" item="vas" separator=",">
                #{vas.属性}
            </foreach>

            )
    </delete>

4、获取自增主键

当插入数据后需要对它进行其他操作时候可以获得它的主键,把它映射到属性里

<insert id="insertUser" useGeneratedKeys="true" keyProperty="需要映射类的属性">
insert into t_user values(null,#{username},#{password},#{age},#{sex})
</insert>

useGeneratedKeys:获得自增主键

keyProperty:主键映射位置

五、动态SQL

1、<if>

<if>只有标签中为true才会拼接标签中的内容

<select id="getEmpListByMoreTJ" resultType="Emp">
   select * from t_emp where 1=1
    <if test="ename != '' and ename != null">
        and ename = #{ename}
    </if>
    <if test="age != '' and age != null">
        and age = #{age}
    </if>
    <if test="sex != '' and sex != null">
        and sex = #{sex}
    </if>
</select>

2、<where>

动态添加where ;自动去掉开头多余的and(不能去掉后面的)

<select id="getEmpListByMoreTJ2" resultType="Emp">
select * from t_emp
    <where>
        <if test="ename != '' and ename != null">
            ename = #{ename}
        </if>
        <if test="age != '' and age != null">
            and age = #{age}
        </if>
        <if test="sex != '' and sex != null">
            and sex = #{sex}
        </if>
    </where>
</select>

3、<trim>

自定义添加或删减前后内容

属性:

prefix:在trim标签中的内容的前面添加某些内容

prefixOverrides:在trim标签中的内容的前面去掉某些内容

suffix:在trim标签中的内容的后面添加某些内容

suffixOverrides:在trim标签中的内容的后面去掉某些内容

<select id="getEmpListByMoreTJ" resultType="Emp">
        select * from t_emp
    <trim prefix="where" suffixOverrides="and">
            <if test="ename != '' and ename != null">
                ename = #{ename} and
            </if>
            <if test="age != '' and age != null">
                age = #{age} and
            </if>
            <if test="sex != '' and sex != null">
                sex = #{sex}
            </if>
    </trim>
</select>

4、choose、when、otherwise

choose、when、 otherwise相当于if.....else if .....else

<select id="getEmpListByChoose" resultType="Emp">
        select <include refid="empColumns"></include> from t_emp
    <where>
        <choose>
            <when test="ename != '' and ename != null">
                ename = #{ename}
            </when>
            <when test="age != '' and age != null">
                age = #{age}
            </when>
            <when test="sex != '' and sex != null">
                sex = #{sex}
            </when>
            <when test="email != '' and email != null">
                email = #{email}
            </when>
        </choose>
    </where>
</select>

5、foreach

前面有提到

6、<SQL>

可以记录一段文本内容,再通过<include>引用

<sql id="empColumns">
        eid,ename,age,sex,did
</sql>

select <include refid="empColumns"></include> from t_emp

六、分布查询

映射类中有实体类或集合时除了使用联合查询外还可以使用分步查询;

例子只分了两步。

只能使用resultMap映射

1、映射类中有类实体

 使用<association>标签

  <resultMap id="EmpAnddeptfenbu" type="com.po.Emp">
        <id column="emp_id" property="empId"></id>
        <result column="emp_name" property="empName"></result>
        <result column="emp_age" property="empAge"></result>

        <association property="dept" fetchType="lazy"
                     select="com.maper.DeptMaper.getEmpAndDeptSte"
                     column="deot_id" >

        </association>
    </resultMap>
    <select id="getEmpAndDeptfenbu" resultMap="EmpAnddeptfenbu">
        select *from emp
        where emp_id=#{empId}
    </select>
property:映射类中的类对象
fetchType:设置立即加载或者延迟加载
column: 数据库字段(传递给第二步的参数)

 select:第二步的接口方的地址引用

第二步正常查找

<!--    getEmpAndDeptSte-->
    <select id="getEmpAndDeptSte" resultType="com.po.Dept">
        select *
        from dept where dept_id=#{deptId}

    </select>

2、映射类内有集合

使用<collection>标签,其他的和前面一致

 <resultMap id="DeptEmpOne" type="com.po.Dept">
        <id column="dept_id" property="deptId"></id>
        <result column="dept_name" property="deptName"></result>
        <collection property="emps" fetchType="lazy"
                    select="com.maper.EmpMaper.getDeptEmpTwo"
                    column="dept_id"></collection>
    </resultMap>
    <select id="getDeptEmpOne" resultMap="DeptEmpOne">
        select *from dept where dept_id=#{deptId}
    </select>
   <select id="getDeptEmpTwo" resultType="com.po.Emp">
        select *from emp where deot_id =#{deptId}
    </select>

七、工具类

sqlSession工厂:
public class SqlSessionUtill {
    public static SqlSession getSqlSession(){
        SqlSession sqlSession =null;
        try {
            InputStream is= Resources.getResourceAsStream("mybatis-cofng.xml");
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder=new  SqlSessionFactoryBuilder();
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
            sqlSession =sqlSessionFactory.openSession(true);

        } catch (IOException e) {
            e.printStackTrace();
        }

        return sqlSession;
    }
}

八、遇到的问题报错

检查数据库连接;

接口配置文件和主要配置文件绑定问题;

接口方法和配置文件绑定;

映射绑定问题;

SQL语句标签内不要使用注释否则会报错

****此专栏仅学习参考使用,发现问题请在评论区指出****

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值