SpringBoot项目集成Mybatis Plus(四)SQL映射文件

实际使用中,都会用到自定义SQL查询语句,并且需要支持分页,因为之前在项目中配置了分页插件,所以用起来很简单。

例如,定义接口getList,接口参数为分页参数和查询条件,

@RequestMapping("getList")
public String getList(Page<Book> page, BookRequest request) {
    try {
        IPage<Book> list = bookService.getList(page, request);
        return list.getRecords().toString();
    } catch (Exception e) {
        e.printStackTrace();
        return "error";
    }
}

只需要在Service接口中定义方法,并且在实现类中实现,

public interface BookService extends IService<Book> {

    IPage<Book> getList(Page<Book> page, BookRequest request);
}
@DS("db1")
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements BookService {
    @Resource
    private BookMapper bookMapper;

    @Override
    public IPage<Book> getList(Page<Book> page, BookRequest request) {
        return bookMapper.getList(page, request);
    }
}

然后在Mapper接口中定义一个方法getList,

public interface BookMapper extends BaseMapper<Book> {

    IPage<Book> getList(Page<?> page, BookRequest request);
}

对应的SQL映射文件如下:

<?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.demo.mybatisplus.demo.book.mapper.BookMapper">
    <select id="getList"
            parameterType="com.demo.mybatisplus.demo.book.entity.BookRequest"
            resultType="com.demo.mybatisplus.demo.book.entity.Book">
      SELECT b.*
      FROM book b
      WHERE b.name like concat(#{param2.name},'%')
    </select>
</mapper>

xml中的param2对应Mapper接口getList方法中的第二个参数。

猜你喜欢

转载自blog.csdn.net/suoyx/article/details/113769434
今日推荐