Mybatis 动态SQL搭建环境的全过程


当前第2页 返回上一页

BlogMapper.java

package com.tian.dao;

import com.tian.pojo.Blog;

public interface BlogMapper {
    //    插入数据
    int addBlog(Blog blog);
}

BlogMapper.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.tian.dao.BlogMapper">
    <insert id="addBlog" parameterType="Blog">
        insert into mybatis.blog(id, title, author, create_time, views)
        values (#{id}, #{title}, #{author}, #{createTime}, #{views});
    </insert>
</mapper>

1.2.2.5 编写IDUtils .java用于生成随机的ID

IDUtils .java

package com.tian.util;

import org.junit.Test;

import java.util.UUID;

@SuppressWarnings("all") // 忽略所有警告
public class IDUtils {
    public static String getId() {
        return UUID.randomUUID().toString().replaceAll("-", "");
    }

    @Test
    public void test() {
        System.out.println(getId());
        System.out.println(getId());
        System.out.println(getId());
        System.out.println(getId());
        System.out.println(getId());
        System.out.println(getId());
    }
}

运行结果:

1.2.2.6 向表中插入数据

Test.java

import com.tian.dao.BlogMapper;
import com.tian.pojo.Blog;
import com.tian.util.IDUtils;
import com.tian.util.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.Date;

public class Test {
    @org.junit.Test
    public void test() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        BlogMapper mapper = sqlSession.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);

        sqlSession.close();
    }
}

运行结果:



现在我们吧表中的数据稍微更改下

总结

到此这篇关于Mybatis 动态SQL搭建环境的文章就介绍到这了,更多相关Mybatis动态SQL环境内容请搜索


打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...