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
<?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.sun.dao.BlogMapper">
<insert id="addBlog" parameterType="com.sun.pojo.Blog">
insert into smbms.blog
(id, title, author, create_time, views)
VALUES
(#{id},#{title},#{author},#{createTime},#{views});
</insert>
</mapper>
1.4.1.注意1
注意1:由于在数据库中的 字段名是create_time,在实体类中的 属性名是createTime,所以我们要修改 驼峰命名自动映射规则
1.4.2.注意2
注意2.在编写sql时,#{}里的名称要和实体类中的名称保持一致 ,尤其是createTime
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<Blog> queryBlogIF(Map map);
}
2.2.Mapper.xml
<select id="queryBlogIF" resultType="com.sun.pojo.Blog" parameterType="map">
select * from blog where 1 = 1
<if test="title != null">
and title like concat('%',#{title},'%')
</if>
</select>
对上面代码的分析:
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<Blog> blogs = mapper.queryBlogIF(map);
for (Blog blog : blogs) {
System.out.println(blog);
}
sqlSession.close();
}