mybatis学习笔记-06

Posted 宏远小七

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mybatis学习笔记-06相关的知识,希望对你有一定的参考价值。


这篇文章来写一些动态SQL的方法,也是我自学mybatis的最后一篇文章。


1.动态SQL环境搭建

环境全视图

1.1、 实体类

package com.ZXF.pojo;

import lombok.Data;
import java.util.Date;

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

1.2、 BlogMapper接口

我数据库的表没有数据,所以我在测试环境是否搭建成功的时候,用插入数据来测试。

public interface BolgMapper {
    int addBolg(Blog blog);
}

1.3、 BlogMapper.xml配置文件

<insert id="addBolg" parameterType="Blog">
    insert into blog (id,title,author,create_time,views)
    values (#{id},#{title},#{author},#{createTime},#{views});
</insert>

注意:在这里有一个属性名没有对应,create_time:createTime,这个可以通过mybatis-config.xml核心配置文件中配置

1.4、 mybatis-config.xml核心配置文件

<settings>
    <!--是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。-->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

1.5、唯一的id标识(Idutil)

这次数据库的id我们让UUID类自己生成,待会下一个知识点可能需要自己改,为了学习到更多知识点,麻烦一点都不重要。

import java.util.UUID;

public class IdUtil {
    public static String getID(){
        //让UUID类生成唯一的id 并将id的-用空来替代
        return UUID.randomUUID().toString().replaceAll("-","");
    }
}

1.6、 测试

@Test
public void addBlogTest(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    BolgMapper mapper = sqlSession.getMapper(BolgMapper.class);
    Blog blog = new Blog();
    blog.setId(IdUtil.getID());
    blog.setTitle("Mybatis");
    blog.setAuthor("小七");
    blog.setCreateTime(new Date());
    blog.setViews(9999);

    mapper.addBolg(blog);

    blog.setId(IdUtil.getID());
    blog.setTitle("Java");
    mapper.addBolg(blog);

    blog.setId(IdUtil.getID());
    blog.setTitle("Spring");
    mapper.addBolg(blog);

    blog.setId(IdUtil.getID());
    blog.setTitle("微服务");
    mapper.addBolg(blog);

    sqlSession.commit();
    sqlSession.close();
}

2、动态SQL之if语句

  1. BlogMapper接口
public interface BolgMapper {
      List<Blog> queryBlogIF(Map map);
}
  1. BlogMapper.xml配置文件
<select id="queryBlogIF" parameterType="map" resultType="Blog">
    select * from blog where 1=1
    <if test="title!=null">
        and title=#{title}
    </if>
    <if test="author!=null">
        and author=#{author}
    </if>
</select>
  1. 测试
@Test
public void queryBlogIF(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    BolgMapper mapper = sqlSession.getMapper(BolgMapper.class);
    HashMap<Object, Object> map = new HashMap<>();
    List<Blog> blogs = mapper.queryBlogIF(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

3、choose、when、otherwise

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

用这些元素进行查询

  1. BlogMapper接口
public interface BolgMapper {
    List<Blog> queryBlogChoose(Map map);
}
  1. BlogMapper.xml
<select id="queryBlogChoose" resultType="Blog" parameterType="map">
    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>

where 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

  1. 测试
@Test
public void queryBlogChoose(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    BolgMapper mapper = sqlSession.getMapper(BolgMapper.class);
    HashMap<Object, Object> map = new HashMap<>();
    map.put("title","Mybatis");
    List<Blog> blogs = mapper.queryBlogChoose(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

4、trim where set

用这些元素更新blog表:

  1. BlogMapper接口
public interface BolgMapper {
    //更新blog
    int updateBlog(Map map);
}
  1. BlogMapper.xml
<update id="updateBlog" parameterType="map">
    update  blog
    <set>
        <if test="title !=null">
            title=#{title}
        </if>
        <if test="author !=null">
            author=#{author}
        </if>
        where id=#{id}
    </set>
</update>
  1. 测试
@Test
public void updateBlog(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    BolgMapper mapper = sqlSession.getMapper(BolgMapper.class);
    HashMap<Object, Object> map = new HashMap<>();
    map.put("title","java基础");
    map.put("id","0b4557c25d0f42d4951da77fb77e9deb");
    int i = mapper.updateBlog(map);
    sqlSession.commit();
    sqlSession.close();
}

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

如果 where 元素与你期望的不太一样,你也可以通过自定义 trim 元素来定制 where 元素的功能。这里就写trim的使用方法,因为我觉得用where和set就OK了,如果有需要的话可以看看官方文档。

5、forEach

用forEach查询博客

  1. BlogMapper接口
public interface BolgMapper {
    //查询blog
    List<Blog> queryBlogForEach(Map map);
}
  1. BlogMapper.xml配置文件
<select id="queryBlogForEach" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>
  1. 测试
@Test
public void queryBlogForEach(){
    SqlSession sqlSession = MybatisUtil.getSqlSession();
    BolgMapper mapper = sqlSession.getMapper(BolgMapper.class);
    HashMap map = new HashMap();
    ArrayList<Integer> ids = new ArrayList<>();
    ids.add(1);
    ids.add(2);
    map.put("ids",ids);
    List<Blog> blogs = mapper.queryBlogForEach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

这是我mybatis自学笔记的第6篇,也是最后一篇文章了。没看过我之前的文章的话可以看看,前5篇的链接↓
mybatis学习笔记-05
mybatis学习笔记-04
mybatis学习笔记-03
mybatis学习笔记-02
mybatis学习笔记-01
这一篇是我之前学习JDBC的时候写的笔记,可以对照着mybatis学习一下,看看mybatis为我们做了多少事情。
java JDBC编程学习笔记


本篇文章到这就结束了。自学不易,如果写得不详细,可以结合官方文档看,也可以评论区交流,这篇文章有可以优化的地方希望大佬指教指教。

以上是关于mybatis学习笔记-06的主要内容,如果未能解决你的问题,请参考以下文章

mybatis学习笔记-06

mybatis学习笔记-06

Mybatis 学习笔记总结

Mybatis学习笔记:动态SQL

mybatis学习笔记三(关联关系)

MyBatis学习笔记11:解决字段名和属性的映射关系