Article Directory
〇、Preparation
database:
create database MyBatis_DB;
use MyBatis_DB;
create table user(
id int primary key auto_increment,
name varchar(32) not null,
pwd varchar(32) not null
);
Then just insert a few pieces of data
Next, create a Maven
project, injection MySql
, MyBatis
, Junit
, LOG4J
dependence
Create a table User
entity class, create an UserMapper
interface, UserMapper.xml
and test class
Next, start to implement paging query
One, Limit realizes paging
The first step is to write the UserMapper
interface
List<User> findUserByLimit(Map<String,Integer> map);
The second step is to write a UserMapper.xml
file and write sql
, where the receiving parameter is one Map
:
<select id="findUserByLimit" resultType="User" parameterType="map">
select * from mybatis_db.user limit #{startPage},#{Page}
</select>
The third step is to write a test class. First, make a Map
storage parameter to be transmitted, then call the method, output the result, and finally close the connection
//获取SqlSession
private SqlSession sqlSession = MyBatisUtils.getSqlSession();
//获取mapper
private UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//limit分页
@Test
public void findUserByLimitTest(){
Map<String,Integer> map = new HashMap<String, Integer>();
map.put("startPage",0);
map.put("Page",5);
List<User> userByLimit = mapper.findUserByLimit(map);
for (User user : userByLimit) {
System.out.println(user);
}
sqlSession.close();
}
Output result:
Two, RowBounds realizes paging | not recommended
The first step is to write the interface
List<User> findUserByRowBounds();
The second step, writing XML
:
<select id="findUserByRowBounds" resultType="User">
select * from mybatis_db.user;
</select>
The third step is to write the test class
//获取SqlSession
private SqlSession sqlSession = MyBatisUtils.getSqlSession();
//RowBounds实现分页
@Test
public void findUserByRowBoundsTest(){
//RowBounds实现
RowBounds rowBounds = new RowBounds(0, 5);
List<User> UserList = sqlSession.selectList(
"com.wzq.mapper.UserMapper.findUserByRowBounds",
null, rowBounds);
for (User user : UserList) {
System.out.println(user);
}
sqlSession.close();
}
test: