二 动态SQL和多对一,一对多

10、多对一处理

子查询,联表查询

  • 多个学生,对应一个老师
  • 对于学生这边而言,关联(association)多个学生,关联一个老师【多对一】
  • 对于老师而言,集合(Collection),一个老师,有很多学生【一对多】

测试环境搭建

  1. 导入lombok

  2. 新建实体类 Teacher,Student

    public class Teacher {
        private int id;
        private String name;
    }
    
    public class Student {
        private int id;
        private  String name;
       //学生要关联一个老师
        private Teacher teacher;
      }
    
  3. 建立Mapper接口

  4. 建立Mapper.XML文件

  5. 在核心配置文件中绑定注册我们的Mapper接口或者文件!【方式很多,随心选】

  6. 测试查询是否能够成功!

按照查询嵌套处理(子查询)

<!--
    思路:
        1. 查询所有的学生信息
        2. 根据查询出来的学生的tid,寻找对应的老师!  子查询
    -->

<select id="getStudent" resultMap="StudentTeacher">
    select * from student
</select>

<resultMap id="StudentTeacher" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--复杂的属性,我们需要单独处理 对象: association 集合: collection -->
    <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"/>
</resultMap>

<select id="getTeacher" resultType="Teacher">
    select * from teacher where id = #{id}
</select>

按照结果嵌套处理(联表查询)

<!--按照结果嵌套处理-->
<select id="getStudent2" resultMap="StudentTeacher2">
    select  s.id sid ,s.name sname,t.name tname
    from student s,teacher t
    where s.tid=t.id
</select>
    <resultMap id="StudentTeacher2" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>

11、一对多

比如:一个老师拥有多个学生! 对于老师而言就是一对多的关系!

实体类

@Data
public class Teacher {
    private int id;
    private String name;
    //一个老师拥有多个学生
    private List<Student> students;
}
@Data
public class Student {
    private int id;
    private  String name;
    private int tid;
  }

按照结果嵌套处理

    <!--按结果嵌套查询-->
    <select id="getTeacher" resultMap="TeacherStudent">
        select s.id sid, s.name sname, t.name tname,t.id tid
        from student s,teacher t
        where s.tid = t.id and t.id = #{tid}
    </select>

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
        <!--复杂的属性,我们需要单独处理 对象: association 集合: collection
        javaType="" 指定属性的类型!
        集合中的泛型信息,我们使用ofType获取
        -->
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>

按照查询嵌套处理

<select id="getTeacher2" resultMap="TeacherStudent2">
    select * from mybatis.teacher where id = #{tid}
</select>

<resultMap id="TeacherStudent2" type="Teacher">
    <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId" column="id"/>
</resultMap>

<select id="getStudentByTeacherId" resultType="Student">
    select * from mybatis.student where tid = #{tid}
</select>

小结

  1. 关联 - association 【多对一】
  2. 集合 - collection 【一对多】
  3. javaType 和 ofType
    1. JavaType 用来指定实体类中属性的类型
    2. ofType 用来指定映射到List或者集合中的 pojo类型,泛型中的约束类型!

注意点

  • 保证SQL的可读性,尽量保证通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题!
  • 如果问题不好排查错误,可以使用日志

在这里插入图片描述
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lGPhwmg0-1653313325896)(D:\Typora\Spring\image-20220522165725183.png)]

面试必考

  • Mysql引擎
  • InnoDB底层原理
  • 索引
  • 索引优化!

12、动态 SQL

什么是动态SQL:动态SQL就是指根据不同的条件生成不同的SQL语句

动态 SQL 元素和 JSTL 或基于类似 XML 的文本处理器相似。在 MyBatis 之前的版本中,有很多元素需要花时间了解。MyBatis 3 大大精简了元素种类,现在只需学习原来一半的元素便可。MyBatis 采用功能强大的基于 OGNL 的表达式来淘汰其它大部分元素。
if
choose (when, otherwise)
trim (where, set)
foreach

实体类

@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;//属性名和字段名不一致 mapUnderscoreToCamelCase开启驼峰命名
    private int views;
}

UUID 便于生成,不会重复,在分布式架构的系统中,很常见,但对于使用了mysql innodb 存储引擎来说,UUID 则不是一个好的选择。

public static  String getID(){
    //主键
    return UUID.randomUUID().toString().replaceAll("-","");
}

添加数据

@Test
public void addBlog(){
    SqlSession sqlSession= MybatisUtils.getSqlSession();
    BlogMapper mapper=sqlSession.getMapper(BlogMapper.class);
//在数据库中添加数据
    Blog blog=new Blog();
    blog.setId(IDUtils.getID());
    blog.setTitle("mybatis");
    blog.setAuthor("loveyourself");
    blog.setCreateTime(new Date());
    mapper.addBlog(blog);

    blog.setId(IDUtils.getID());
    blog.setTitle("spring");
    mapper.addBlog(blog);

    blog.setId(IDUtils.getID());
    blog.setTitle("springboot");
    mapper.addBlog(blog);

    blog.setId(IDUtils.getID());
    blog.setTitle("springCloud");
    mapper.addBlog(blog);
    sqlSession.close();
}

IF

//查询博客
List<Blog> queryBlogIF(Map map);
<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from mybatis.blog
    where 1=1
    <if test="title!=null">
        and title=#{title}
    </if>
    <if test="author!=null">
        and author=#{author}
    </if>
</select>

测试

@Test
public void queryBlogIF() {
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    Map<String, String> map = new HashMap<>();
    map.put("title", "mybatis");
    map.put("author","loveyourself");
    List<Blog> list=mapper.queryBlogIF(map);
    for (Blog s:list){
        System.out.println(s);
    }
    sqlSession.close();
}

choose (when, otherwise)

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

<!-- 类似于java中的case智慧选择其中一个去实现-->
<select id="queryBlogChoose" parameterType="map" resultType="blog">
    select * from mybatis.blog
   <where>
       <choose>
           <when test="title!=null">
               title=#{title}
           </when>
           <when test="author!=null">
               and author=#{author}
           </when>
            <otherwise>
                and views=#{views}
            </otherwise>
       </choose>
   </where>
</select>

trim (where,set)

动态更新语句set 元素可以用于动态包含需要更新的列,忽略其它不更新的列。

set 元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号(这些逗号是在使用条件语句给列赋值时引入的)。

<update id="updateBlog" parameterType="map">
    update mybatis.blog
    <set>
        <if test="title!=null">
            title=#{title}
        </if>
        <if test="author!=null">
            and author=#{author}
        </if>
    </set>
where id=#{id}
</update>

所谓动态sql本质还是sql语句,只是我们可以在sql层面,去执行一些逻辑代码

SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用!

  1. 使用SQL标签抽取公共的部分

    <sql id="if-title-author">
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </sql>
    
  2. 在需要使用的地方使用Include标签引用即可

    <select id="queryBlogIF" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <include refid="if-title-author"></include>
        </where>
    </select>
    

注意事项:

  • 最好基于单表来定义SQL片段!
  • 不要存在where标签(就用if的就挺好)

foreach

动态SQL的另外一个常用的操作需求是对一个集合进行遍历,通常实在构建IN条件语句的时候。

foreach元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头于结尾的字符串以及在迭代结果之间反之分隔符。这个元素是很智能的,因此它不会偶然地附加多余的分隔符。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-qc9C0hiY-1653313325901)(D:\Typora\Spring\image-20220523210620674.png)]

<!--
原生 select * from mybatis.blog where 1=1 and (id=1 or id = 2 or id=3)
    我们传递一个万能的map,这个map中可以存在一个集合collection
    open开头是什么,close结尾是什么,separator分隔符是什么
-->
    <select id="queryBlogForeach" parameterType="map" resultType="blog">
        select * from mybatis.blog
        <where>
            <foreach item="id" collection="ids" open="and (" close=")" separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>
@Test
public void queryBlogForeach(){
    SqlSession sqlSession=MybatisUtils.getSqlSession();
    BlogMapper mapper=sqlSession.getMapper(BlogMapper.class);
    Map map=new HashMap();
    List<Integer> ids=new ArrayList<Integer>();
    ids.add(1);
    ids.add(3);
    map.put("ids",ids);
    List<Blog> list=mapper.queryBlogForeach(map);
    sqlSession.close();
}

动态SQL就是在拼接SQL语句,我们只要保证SQL的正确性按照SQL的格式,去排列组合就可以了

就是:现在Mysql中写出完整的SQL,再对应的去修改成为我们的动态SQL实现通用即可!

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值