mybatis学习二之增删改查

1.增加,并返回主键的id:

配置文件不详细说,见上一篇博客:mybatis学习一之入门示例

在BlogDao中增加接口:

    /**
     * 插入后返回id
     *
     * @param blog
     */
    public void insertCacheId(Blog blog) {
        mapper.insertCacheId(blog);
        this.close();
    }

mapper文件增加接口:

void insertCacheId(Blog blog);

配置文件中增加:

    <!--插入后返回id:select @@identity-->
    <insert id="insertCacheId" parameterType="Blog">
        insert into Blog(id, title, author_id, state, featured, style)
        values
        (#{id}, #{title}, #{authorId}, #{state}, #{featured}, #{style})
        <selectKey resultType="int" keyProperty="id" order="AFTER">
        select @@identity
        </selectKey>
    </insert>

增加测试单元:

    @Test
    public void testInsertCacheBlogId() {
        Blog build = Blog.builder()
                .authorId(1)
                .state("ACTIVE")
                .style("333")
                .featured(false)
                .title("三国演义")
                .build();
        new BlogDao().insertCacheId(build);
        logger.info("after blog is:{}", build);
    }

测试结果:

 

2.查询所有数据,步骤同上:

    public List<Blog> selectAllBlogs() {
        return mapper.selectAllBlogs();
    }

 

 List<Blog> selectAllBlogs();
    <select id="selectAllBlogs" resultType="Blog">
        select * from Blog
    </select>
    @Test
    public void testSelectAllBlogs() {
        final List<Blog> blogs = new BlogDao().selectAllBlogs();
        blogs.stream().forEach(blog -> logger.info(blog));
    }

3.模糊查询

    public List<Blog> selectBlogsByTitle(String title) {
        return mapper.selectBlogsByTitle(title);
    }

 

List<Blog> selectBlogsByTitle(String title);

 

    <select id="selectBlogsByTitle" resultType="Blog">
        select * from Blog where title like concat('%', #{title}, '%')
    </select>
    @Test
    public void testSelectBlogsByTitle() {
        final List<Blog> blogs = new BlogDao().selectBlogsByTitle("三");
        blogs.stream().forEach(blog -> logger.info(blog));
    }

测试结果:

4.多条件查询

    public List<Blog> selectBlogsByCondition(Map<String, Object> map) {
        return mapper.selectBlogsByCondition(map);
    }

 

List<Blog> selectBlogsByCondition(Map<String, Object> map);

 

    <select id="selectBlogsByCondition" resultType="Blog">
        select * from Blog where title like concat('%', #{title}, '%') and state = #{state}
    </select>

 

    @Test
    public void testSelectBlogsByCondition() {
        Map<String, Object> map = new HashMap<>();
        map.put("title", "a");
        map.put("state", "Active");
        final List<Blog> blogs = new BlogDao().selectBlogsByCondition(map);
        blogs.stream().forEach(blog -> logger.info(blog));
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值