引入依赖
org.mybatis.spring.boot
mybatis-spring-boot-starter
2.0.0
tk.mybatis
mapper-spring-boot-starter
2.0.0
mysql
mysql-connector-java
runtime
com.alibaba
druid-spring-boot-starter
1.1.14
com.github.pagehelper
pagehelper-spring-boot-starter
1.2.10
修改配置文件
server:
port: 8080
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/admin?useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: root
mybatis:
#加载mapper文件
mapper-locations: classpath:mapper/*.xml
#设置实体类别名
#type-aliases-package: demo.springboot.mybatismapperpagehelper.domain
#加载mybatis全局配置文件
#config-location: classpath:mybatis/SqlMapConfig.xml
mapper:
#通用mapper的类,可以多个,不要和业务dao放到一起
mappers: demo.springboot.mybatismapperpagehelper.basedao.BaseMapper
BaseMapper
//继承tkmapper中的接口,更多可查看官方文档
//Mapper是基础的增删改查,根据Example查询等
//MySqlMapper是对mysql的一些操作
public interface BaseMapper extends Mapper, MySqlMapper {
}
实体类
@Data
public class SysUser {
//根据主键查询时必须要有@Id注解,否则会报错
@Id
private Long id;
private String username;
private String password;
private String nickname;
private Integer age;
}
DAO
//继承第三步中的BaseMapper,泛型是实体类
public interface SysUserDAO extends BaseMapper {
}
扫描dao
@SpringBootApplication
//这里使用的扫描注解不是mybatis的,是通用mapper的注解
@MapperScan("demo.springboot.mybatismapperpagehelper.dao")
public class MybatisMapperPagehelperApplication {
public static void main(String[] args) {
SpringApplication.run(MybatisMapperPagehelperApplication.class, args);
}
}
测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class MybatisMapperPagehelperApplicationTests {
@Autowired
private SysUserDAO userDAO;
@Test
public void testSelectByPrimaryKey() {
//根据主键查询
SysUser sysUser = userDAO.selectByPrimaryKey(1L);
System.out.println(sysUser);
}
@Test
public void testSelectAll() {
//查询所有数据
List sysUsers = userDAO.selectAll();
System.out.println(sysUsers);
}
@Test
public void testPageHelper(){
//第一个参数为页数,第二个为条数。对这个方法后的第一个sql生效,
//单表分页,一对一分页正确。一对多,多对多分页会出现错误
//PageHelper.startPage(1, 10);
//根据id倒序排序
PageHelper.startPage(1, 2, "id desc");
List sysUsers = userDAO.selectAll();
//获取分页数据
PageInfo pageInfo = new PageInfo<>(sysUsers);
//获取总条数
System.out.println(pageInfo.getTotal());
//获取分页页数
System.out.println(pageInfo.getPageNum());
//获取分页条数
System.out.println(pageInfo.getPageSize());
//获取分页数据,即上面查询到的sysUsers
System.out.println(pageInfo.getList());
}
}
测试根据主键查询
控制台日志:
==> Preparing: SELECT id,username,password,nickname,age FROM sys_user WHERE id = ?
==> Parameters: 1(Long)
<== Total: 1
测试查询所有数据
控制台日志:
==> Preparing: SELECT id,username,password,nickname,age FROM sys_user
==> Parameters:
<== Total: 3
测试分页插件
控制台日志:
==> Preparing: SELECT id, username, password, nickname, age FROM sys_user order by id desc LIMIT ?
==> Parameters: 2(Integer)
<== Total: 2
注:通用mapper只能做一些简单的操作,业务复杂的还需要自己手动实现。
分页插件不需要格式化页数((pageNum-1)*pageSize),自己写sql时需要格式化页数
作者公众号