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

本文介绍使用MyBatis实现数据的插入并获取自增ID、查询所有记录、模糊查询及多条件查询的方法。通过具体示例展示了如何在Mapper接口中定义方法,在XML配置文件中编写SQL语句,以及进行单元测试。
1208

被折叠的 条评论
为什么被折叠?



