引入依賴
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時需要格式化頁數
作者公衆号