Mybatis—动态sql—if语句

1.环境搭建(这里先以插入数据作为一个测试)

1.1.添加一个utils工具类

这个工具类的功能是获取UUID,为了让数据库id字段不重复,公司业务会用到

public class IDutils {
    public static String getId(){
        return UUID.randomUUID().toString().replaceAll("-","");
    }
1.2.实体类
public class Blog {
    private String id;
    private String title;
    private String author;
    private Date createTime;
    private int views;
}
1.3.Mapper接口
public interface BlogMapper {

    int addBlog(Blog blog);
}
1.4.Mapper.xml




    
        insert into smbms.blog
            (id, title, author, create_time, views)
        VALUES
            (#{id},#{title},#{author},#{createTime},#{views});
    

1.4.1.注意1
注意1:由于在数据库中的 字段名是create_time,在实体类中的 属性名是createTime,所以我们要修改 驼峰命名自动映射规则

Mybatis—动态sql—if语句_第1张图片

1.4.2.注意2

注意2.在编写sql时,#{}里的名称要和实体类中的名称保持一致 ,尤其是createTime

 Mybatis—动态sql—if语句_第2张图片

1.5.测试类
    @Test
    public void addTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

        Blog blog = new Blog();
        blog.setId(IDutils.getId());
        blog.setTitle("MyBatis如此简单");
        blog.setAuthor("两仪式quq");
        blog.setCreateTime(new Date());
        blog.setViews(999);

        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);


        //提交事务已经改成自动化提交了


        sqlSession.close();
    }

2.IF标签(以查询为例子来讲解)

2.1.Mapper接口
public interface BlogMapper {

    List queryBlogIF(Map map);
}
2.2.Mapper.xml
    

 对上面代码的分析:

Mybatis—动态sql—if语句_第3张图片

2.3.测试类
    @Test
    public void selectIfTest(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();

        BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
        HashMap map = new HashMap();
        map.put("title","j");


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

        sqlSession.close();
    }
 2.4.查询结果

你可能感兴趣的:(mybatis,sql,java)