Mybatis的ResultMap与limit分页查询
2024-09-02 08:28:33
ResultMap主要解决的是:属性名和字段不一致
如果在pojo中设置的是一个名字,在数据库上又是另一个名字,那么查询出来的结果或者其他操作的结果就为null。
//在pojo中
private String password;
private String uname; //在userMapper中
selcet uname,pwd from user; //显示结果
//password==null;
//uname==123;
解决办法:
可以手动映射:resultMap
//返回值类型为:resultMap
<select id="selectUserById" resultMap="UserMap">
select id , name , pwd from user where id = #{id}
</select> //编写resultMap,实现手动映射
<resultMap id="UserMap" type="User">
<!-- id为主键 -->
<id column="id" property="id"/>
<!-- column是数据库表的列名 , property是对应实体类的属性名 -->
<result column="name" property="name"/>
<result column="pwd" property="password"/>
</resultMap>
limit分页查询
limit语法:
SELECT * FROM table LIMIT stratIndex,pageSize;
//stratIndex:从第几个字段开始查询 pageSize:查询多少个字段
SELECT * FROM table LIMIT 5,10; // 检索记录行 6-15
#为了检索从某一个偏移量到记录集的结束所有的记录行,可以指定第二个参数为 -1:
SELECT * FROM table LIMIT 95,-1; // 检索记录行 96-last.
#如果只给定一个参数,它表示返回最大的记录行数目:
SELECT * FROM table LIMIT 5; //检索前 5 个记录行
#换句话说,LIMIT n 等价于 LIMIT 0,n。
mapper:
<select id="selectUser" parameterType="map" resultType="user">
select * from user limit #{startIndex},#{pageSize}
</select>
接口:
//选择全部用户实现分页
List<User> selectUser(Map<String,Integer> map);
测试类
//分页查询 , 两个参数startIndex , pageSize
@Test
public void testSelectUser() {
SqlSession session = MybatisUtils.getSession();
UserMapper mapper = session.getMapper(UserMapper.class);
int currentPage = 1; //第几页
int pageSize = 2; //每页显示几个
Map<String,Integer> map = new HashMap<String,Integer>();
map.put("startIndex",(currentPage-1)*pageSize);
//起始位置=(当前页面-1)* 显示多少个字段
map.put("pageSize",pageSize);
List<User> users = mapper.selectUser(map);
for (User user: users){
System.out.println(user);
}
session.close();
}
最新文章
- CF735D Taxes 哥德巴赫猜想\判定素数 \进一步猜想
- 剑指offer系列24---数组中重复的数字
- POJ 1734
- win7旗舰版通知windows不是正版副本解决方法
- #pragma execution_character_set的意义
- 修改Hosts不生效的一个场景-web(转)
- 开涛spring3(2.2) - IoC 容器基本原理及其helloword
- Redis基本数据类型
- CentOs 7 中安装tomcat8
- 解决浏览器跨域限制方案之WebSocket
- jmeter 压力测试(一)一个简单的登录
- php正则提取html图片(img)src地址与任意属性的方法
- Bootstrap导航
- 自学Zabbix之路15.3 Zabbix数据库表结构简单解析-Triggers表、Applications表、 Mapplings表
- python3笔记(二)Python语言基础
- QQ Protect 的删除
- python记录_day23 正则表达式 re模块
- Git版本退回和修改
- Codeforces Round #519 题解
- NHibernate.3.0.Cookbook第一章第六节Handling versioning and concurrency的翻译