Mybatis(3)

4 篇文章 0 订阅
4 篇文章 0 订阅

朋友们大家好,我们又见面了,回顾上一章我们简单了解了Mybatis优化等,下面让我们先来简单的回顾一下:

回顾:

1. mybatis的优化

① 引入数据库属性文件

② 引入日志文件

③ 解决列名和属性名不一致。【1】起别名--与属性名一致  【2】resultMap完成列和属性的映射。

2. 转义符: <![CDATA[sql]]>

3. 多个参数的。@Param("参数名")   #{参数名}

4. dao接口结合映射文件。namespace要和接口名一致   id要和接口中的方法名一致。

回顾结束,我们废话不多说,开始今天的内容:

1. 链表查询。

1.1 多对一

① 根据订单id查询订单信息以及该订单对应的用户信息。

第一种方式 通过链表查询:

首先先准备两个表:

员工表:

部门表:

 

 ② 新建我们要用的两个实体类

 

 ③ 同样我们需要在新建两个接口

 ④ 然后新建一个我们的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="com.fan.dao.YuanGongDao">
    <resultMap id="My01" type="com.fan.entity.Yuangong">
        <id property="yid" column="yid"/>
        <result property="yname" column="yname"/>
        <result property="bid" column="bid"/>

           <!--association:表示多对一
            property:表示对象属性名
            javaType:表示该对象所属的类型
            autoMapping必须写
        -->

        <association property="buMen" javaType="com.fan.entity.BuMen" autoMapping="true">

            <!--User和User表的对应关系-->

            <id property="bid" column="bid"/>
        </association>
    </resultMap>

<!--注意:使用了resultMap不能在使用resultType-->

    <select id="SelectId" resultMap="My01">
        select * from yuangong yg join bumen bm on yg.bid=bm.bid where yg.yid=#{yid}
    </select>



   
</mapper>

⑤ 开始测试(测试之前记得把我们的映射文件给拉过来,不然会报错)

⑥ 测试结果如下:

第二种方式 通过嵌套查询。----两次查询

① 新建我们的BuMenMapper.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="com.fan.dao.BuMenDao">
    <select id="SelectId" resultType="com.fan.entity.BuMen">
        select * from bumen where bid=#{bid}
    </select>
</mapper>

② 然后在我们的YuanGongMapper.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="com.fan.dao.YuanGongDao">

    <resultMap id="My02" type="com.fan.entity.Yuangong">
    <id property="yid" column="yid"/>
    <result property="yname" column="yname"/>
    <result property="bid" column="bid"/>
        <association property="buMen" javaType="com.fan.entity.BuMen"
        column="bid" select="com.fan.dao.BuMenDao.SelectId">
        </association>
    </resultMap>
    <select id="SelectId2" resultMap="My02">
        select * from yuangong where yid=#{yid}
    </select>
</mapper>

③ 测试

 1.2 一对多【了解就可以,两者相差不大】

从一的一方查询多的一方:

例如:一个班级里面有多个学生

① 同样建立我们需要的类和接口

 

 ② 建立ClassMapper.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="com.fan.dao.ClassDao">
    <resultMap id="My03" type="com.fan.entity.Class1">
        <id property="id" column="id"/>
        <result property="cname" column="cname"/>
        <collection property="stus" ofType="com.fan.entity.Stu" autoMapping="true">
            <id property="sid" column="sid"/>
            <result property="sname" column="sname"/>
            <result property="cid" column="cid"/>
        </collection>
    </resultMap>
    <select id="SelectId" resultMap="My03">
        select * from class c join stu s on c.id=s.cid where id=#{id}
    </select>
</mapper>

 ③ 加入映射文件

 ④ 测试

import com.fan.dao.ClassDao;
import com.fan.entity.Class1;
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 org.junit.Before;
import org.junit.Test;

import java.io.Reader;

/**
 * @program: laofan-day01
 * @description: 测试
 * @author: 老范
 * @create: 2021-12-04 16:16
 **/
public class TestClass {
    private SqlSession sqlSession;
    @Before
    public void before()throws Exception{
        Reader resourceAsReader = Resources.getResourceAsReader("mybatis.xml");
        SqlSessionFactory build = new SqlSessionFactoryBuilder().build(resourceAsReader);
        sqlSession = build.openSession();
    }
    @Test
    public void SelectId(){
        ClassDao classDao = sqlSession.getMapper(ClassDao.class);
        Class1 class1 = classDao.SelectId(1);
        System.out.println(class1);
    }
}

 2. 动态SQL语句

2.1 sql语句根据条件而发生改变。

 准备我们要用的表

2.2 if和where一起用

 ① 新建我们的实体类和接口

 ②编写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="com.fan.dao.BookDao">
    <resultMap id="Map06" type="com.fan.entity.Book">
        <id property="id" column="book_id"/>
        <result property="name" column="book_name"/>
        <result property="author" column="book_author"/>
        <result property="price" column="book_price"/>
        <result property="pub" column="book_pub"/>
    </resultMap>

    <select id="SelectAll" resultMap="Map06">
        /*where: 可以帮你添加where关键 并且把第一个的and | or 去除
        if:判断要查找的内容是否为空或者空字符
        */
        select * from book_info
        <where>
            <if test="bookname!=null and bookname!=''">
                and book_name=#{bookname}
            </if>
            <if test="bookauthor!=null and bookauthor!=''">
                and book_author=#{bookauthor}
            </if>
        </where>
               
    </select>
</mapper>

 ③ 测试

@Test
    public void testSelect01(){
        BookDao bookDao = session.getMapper(BookDao.class);
        Map<String,Object> map=new HashMap<String,Object>();//从网页中得到参数值 并且封装到map对象中。
        map.put("bookname","金瓶梅");
        map.put("author","罗贯中");
        List<Book> list = bookDao.bookauthor(map);

    }

2.3 [choose when otherwise] 和where(步骤如上)

编写Mapper

<!--choose +where
      when:当条件满足时不会执行下面的when和other  都不满足则执行otherwise

-->
<select id="findByCondition2" resultMap="map">
     select * from book
     <where>
          <choose>
               <when test="bookname!=null and bookname!=''">
                    and book_name=#{bookname}
               </when>
             <when test="author!=null and author!=''">
                 and book_author=#{author}
             </when>
             <otherwise>
                  and book_price>35
             </otherwise>
         </choose>
     </where>
</select>

测试

@Test
    public void testSelect02(){
        BookDao bookDao = session.getMapper(BookDao.class);
        Map<String,Object> map=new HashMap<String,Object>();//从网页中得到参数值 并且封装到map对象中。
//        map.put("name","金瓶梅");
//        map.put("author","罗贯中");
        List<Book> list = bookDao.方法(map);
    }

2.4 set标签。修改部分字段。

编写Mapper

<!--修改部分列的值。
      set 可以帮你添加set关键字 并且去除最后的逗号。
-->
<update id="update">
    update book
    <set>
         <if test="name!=null and name!=''">
              book_name=#{name},
         </if>
         <if test="author!=null and author!=''">
             book_author=#{author},
         </if>
         <if test="pub!=null and pub!=''">
              book_pub=#{pub},
         </if>
         <if test="price!=null">
              book_price=#{price},
         </if>
    </set>
    where book_id=#{id}
</update>

测试

@Test
public void testUpdate(){
    BookDao bookDao = session.getMapper(BookDao.class);
    Book book=new Book();
    book.setAuthor("金庸");
    book.setName("神雕效率");
    book.setId(1002);
    bookDao.update(book);
    session.commit();
}

2.5  foreach 批量删除。

编写Mapper

 <!--
     delete from book_info where id in(1001,1002,1003)

       in (1001,1002,1003)
       foreach:
         collection:要遍历的集合和数组名
         item: 每次遍历时赋值的元素变量名
         open: 以什么开始
         close:以什么结束
         separator: 分隔符
    -->
    <delete id="batchDelete">
        delete from book where book_id in
        <foreach collection="ids" item="id" open="(" close=")" separator=",">
             #{id}
        </foreach>
    </delete>

测试

@Test
public void testUpdat2e(){
    BookDao bookDao = session.getMapper(BookDao.class);
    int [] ids={1001,1002,1003};
    bookDao.batchDelete(ids);
    session.commit();
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis是一个开源的持久层框架,它可以帮助开发者简化数据库访问的过程。 MyBatis3文档是指MyBatis3框架的官方文档,提供了详细的使用说明和示例代码,方便开发者学习和使用该框架。 MyBatis3文档主要包含以下几个方面的内容: 1. 框架概述:介绍了MyBatis的特点和优势,以及与其他ORM框架的对比,帮助开发者了解框架的整体架构和设计理念。 2. 配置文件:详细介绍了MyBatis的配置文件,包括数据库连接信息、映射文件路径、插件配置等,开发者可以根据需要进行相应的配置。 3. SQL映射文件:说明了如何编写SQL映射文件,包括SQL语句的编写、参数的传递、结果的映射等,开发者可以根据需求编写自己的SQL语句。 4. 使用示例:提供了一些常见的使用示例,包括基本的CRUD操作、复杂的查询、分页查询等,方便开发者学习和参考。 5. 高级特性:介绍了一些高级特性,如动态SQL、自动映射、缓存配置等,开发者可以根据实际需求选择使用。 通过仔细阅读MyBatis3文档,开发者可以全面了解MyBatis的各个方面,掌握使用该框架的技巧和方法,提高开发效率和代码质量。此外,MyBatis3文档还提供了丰富的示例代码,方便开发者快速上手和理解框架的使用方式。总之,MyBatis3文档对于学习和使用MyBatis框架来说是非常重要和必要的参考资料。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值