JavaEE(5)Mybatis多对一、一对多、动态SQL

1. Mybatis中多对一查询

1. 多对一的理解
(1)多个学生对应一个老师
(2)对于学生这边,就是一个多对一现象,即从多个学生这边关联一个老师
2. 数据库的设计
(1)sql语句

CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8


INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师');


CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8


 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('1', '小明', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('2', '小红', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('3', '小张', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('4', '小李', '1');
INSERT INTO `student` (`id`, `name`, `tid`) VALUES ('5', '小王', '1');

(2)架构设计
在这里插入图片描述
3. 环境搭建
(1)编写实体类对象

@Data
public class Teacher {
    private int id;
    private String name;
}
@Data
public class Student {
    private int id;
    private String name;
    private Teacher teacher;
}

(2)编写实体类对应的Mapper接口

public interface StudentMapper {
}
public interface TeacherMapper {
}

(3)编写Mapper接口对应的Mapper.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.nelws.dao.TeacherMapper">

</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.nelws.dao.StudentMapper">

</mapper>

(4)按查询结果进行嵌套处理:类似于sql中的连表查询

public interface StudentMapper {
    List<Student> getStudents();
}
<mapper namespace="com.nelws.dao.StudentMapper">

    <!--
        按查询结果进行嵌套处理:类似于sql中的连表查询
        思路:直接查询出结果,进行结果集映射
    -->
    <select id="getStudents" resultMap="StudentTeacher">
        select s.id sid,s.name sname,t.name tname
        from student s,teacher t
        where s.tid = t.id
    </select>

    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
        <!--关联对象property 关联对象在Student实体类中的属性-->
        <association property="teacher" javaType="Teacher">
            <result property="name" column="tname"/>
        </association>
    </resultMap>
</mapper>

(5)测试

    @Test
    public void test01(){
        SqlSession sqlSession = MyBaitsUtils.getSqlSession();
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        List<Student> students = mapper.getStudents();
        for (Student student : students) {
            System.out.println(student);
        }
        sqlSession.close();
    }

在这里插入图片描述

2. 一对多

1. 一对多的理解
(1)一个老师拥有多个学生
(2)对于老师这边,就是一个一对多现象,一个老师拥有许多学生(集合)
2. 环境搭建
(1)实体类

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

(2)剩下的与之前一样
(3)按查询结果嵌套处理

public interface TeacherMapper {
    Teacher getTeacher(int id);
}
<mapper namespace="com.nelws.dao.TeacherMapper">
    <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 = #{id}
    </select>

    <resultMap id="TeacherStudent" type="Teacher">
        <result property="name" column="tname"/>
        <collection property="students" ofType="Student">
            <result property="id" column="sid"/>
            <result property="name" column="sname"/>
            <result property="tid" column="tid"/>
        </collection>
    </resultMap>
</mapper>

(4)测试

public class Test01 {
    @Test
    public void test01(){
        SqlSession sqlSession = MyBaitsUtils.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(1);
        System.out.println(teacher);
        sqlSession.close();
    }
}

在这里插入图片描述

3. 多对一,一对多总结

1. 关联:association
2. 集合:collection
3. association用于一对一与多对一,collection用于一对多
4. JavaType和ofType的理解
	1. JavaType是用来指定domain中属性的类型(关联对象)
	2. ofType指定的是映射到List集合属性中domain的类型

4. 动态SQL

1. 概念:动态SQL指的是根据不同的查询条件 , 生成不同的Sql语句
2. 分类
(1)if
(2)choose(when,otherwise)
(3)trim(where,set)
(4)foreach
3. 好处:我们之前写的 SQL 语句都比较简单,如果有比较复杂的业务,我们需要写复杂的 SQL 语句,往往需要拼接,而拼接 SQL ,稍微不注意,由于引号,空格等缺失可能都会导致错误。那么怎么去解决这个问题呢?这就要使用 mybatis 动态SQL,通过 if, choose, when, otherwise, trim, where, set, foreach等标签,可组合成非常灵活的SQL语句,从而在提高 SQL 语句的准确性的同时,也大大提高了开发人员的效率
4. 搭建环境
(1)数据库表:blog

CREATE TABLE `blog` (
  `id` varchar(50) NOT NULL COMMENT '博客id',
  `title` varchar(100) NOT NULL COMMENT '博客标题',
  `author` varchar(30) NOT NULL COMMENT '博客作者',
  `create_time` datetime NOT NULL COMMENT '创建时间',
  `views` int(30) NOT NULL COMMENT '浏览量'
) ENGINE=InnoDB DEFAULT CHARSET=utf8

(2)创建mybatis基础工程
(3)编写IDUtils

public class IDUtils {
    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}

(4)实体类Blog

@Data
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}

(5)编写Mapper接口及Mapper.xml

public interface BlogMapper {
}
<?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.nelws.dao.BlogMapper">

</mapper>

(6)由于数据库的创建时间与实体类的创建时间字段名不同,在mybatis核心配置文件设置,下划线驼峰自动转换

<settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

(7)插入原始数据

  • 编写接口
public interface BlogMapper {
    int addBlog(Blog blog);
}
  • Mapper.xml中编写sql
<?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.nelws.dao.BlogMapper">
    <insert id="addBlog" parameterType="Blog">
        insert into blog(id,title,author,create_time,views)
        values (#{id},#{title},#{author},#{createTime},#{views})
    </insert>
</mapper>
  • 测试
    @Test
    public void test01(){
        SqlSession session = MyBaitsUtils.getSqlSession();
        BlogMapper mapper = session.getMapper(BlogMapper.class);

        Blog blog = new Blog();
        blog.setId(IDUtils.getId());
        blog.setTitle("Mybatis如此简单");
        blog.setAuthor("老王");
        blog.setCreateTime(new Date());
        blog.setViews(9999);

        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("Java如此简单");
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("Spring如此简单");
        mapper.addBlog(blog);

        blog.setId(IDUtils.getId());
        blog.setTitle("微服务如此简单");
        mapper.addBlog(blog);

        session.close();
    }

5. if语句
(1)需求:根据作者名字和博客名字来查询博客!如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
(2)编写接口

public interface BlogMapper {
    int addBlog(Blog blog);

    //if语句
    List<Blog> queryBlogIf(Map map);
}

(3)Mapper.xml中编写sql语句

    <!--
        if语句
        根据作者名字和博客名字来查询博客!
        如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
        select * from blog where title = #{title} and author = #{author}
    -->
    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from blog where
        <if test="title != null">
            title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </select>

(4)测试

    @Test
    public void test02(){
        SqlSession sqlSession = MyBaitsUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("title","Mybatis如此简单");
        map.put("author","老王");

        List<Blog> blogs = mapper.queryBlogIf(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }
    }

(5)小bug:这样写我们可以看到,如果 author 等于 null,那么查询语句为 select * from user where title=#{title},但是如果title为空呢?那么查询语句为 select * from user where and author=#{author},这是错误的 SQL 语句,如何解决呢?请看下面的 where 语句!

    <!--
        if语句
        根据作者名字和博客名字来查询博客!
        如果作者名字为空,那么只根据博客名字查询,反之,则根据作者名来查询
        select * from blog where title = #{title} and author = #{author}
    -->
    <select id="queryBlogIf" parameterType="map" resultType="Blog">
        select * from blog 
        <where>
            <if test="title != null">
                title = #{title}
            </if>
            <if test="author != null">
                and author = #{author}
            </if> 
        </where>      
    </select>

这个“where”标签会知道如果它包含的标签中有返回值的话,它就插入一个 ‘where’。此外,如果标签返回的内容是以AND或OR开头的,则它会剔除掉

6. set语句
(1)需求:更新操作
(2)编写接口

    //set语句
    int updateBlogSet(Map map);

(3)编写Mapper.xml中的sql

    <!--set语句-->
    <update id="updateBlogSet" parameterType="map">
        update blog
        <set>
            <if test="title != null">
                title = #{title},  【注意,set后面要加","】
            </if>
            <if test="author != null">
                author = #{author}
            </if>
        </set>
        where id = #{id}
    </update>

(4)测试

    @Test
    public void test03(){
        SqlSession sqlSession = MyBaitsUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("title","动态sql");
        map.put("author","Wang");
        map.put("id","be74fc9a524d48dbba04b64101643eee");

        mapper.updateBlogSet(map);

        sqlSession.close();
    }

7. choose语句
(1)概述:有时候,我们不想用到所有的查询条件,只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句
(2)编写接口

    //choose
    List<Blog> queryBlogChoose(Map map);

(3)编写Mapper.xml的sql语句

    <!--choose语句-->
    <select id="queryBlogChoose" parameterType="map" resultType="Blog">
        select * from 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>

(4)测试

    @Test
    public void test04(){
        SqlSession sqlSession = MyBaitsUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("title","动态sql");
        map.put("author","老王");
        map.put("views",9999);
        List<Blog> blogs = mapper.queryBlogChoose(map);
        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }

8. sql片段
(1)概念:有时候可能某个 sql 语句我们用的特别多,为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用
(2)提取sql片段

<sql id="if-title-author">
    <if test="title != null">
        title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>

(3)使用sql片段

<select id="queryBlogIf" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
        <include refid="if-title-author"></include>
        <!-- 在这里还可以引用其他的 sql 片段 -->
    </where>
</select>

(4)注意:①最好基于单表来定义 sql 片段,提高片段的可重用性。②在 sql 片段中不要包括 where

9. foreach语句
(1)需求:将bolg的id改为1,2,3,查询blog 表中 id 分别为1,2,3的博客信息
(2)编写接口

    //foreach
    List<Blog> queryBlogForeach(Map map);

(3)编写Mapper.xml中的sql语句

参数解释
	collection:指定输入对象中的集合属性
    item:每次遍历生成的对象
    open:开始遍历时的拼接字符串
    close:结束时拼接的字符串
    separator:遍历对象之间需要拼接的字符串
    <!--foreach-->
    <select id="queryBlogForeach" parameterType="map" resultType="Blog">
        select * from blog
        <where>
            <!--
                collection:指定输入对象中的集合属性
                item:每次遍历生成的对象
                open:开始遍历时的拼接字符串
                close:结束时拼接的字符串
                separator:遍历对象之间需要拼接的字符串
                select * from blog where 1=1 and (id=1 or id=2 or id=3)
            -->
            <foreach collection="ids" item="id" open="and (" close=")" separator="or">
                id = #{id}
            </foreach>
        </where>
    </select>

(4)测试

    @Test
    public void test05(){
        SqlSession sqlSession = MyBaitsUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        HashMap map = new HashMap();
        ArrayList<Integer> ids = new ArrayList<Integer>();
        ids.add(1);
        ids.add(2);
        ids.add(3);
        map.put("ids",ids);

        List<Blog> blogs = mapper.queryBlogForeach(map);

        for (Blog blog : blogs) {
            System.out.println(blog);
        }

        sqlSession.close();
    }
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值