02_MyBatis分页&注解开发

1 分页

在学习mybatis等持久层框架的时候,会经常对数据进行增删改查操作,使用最多的是对数据库进行查询操作,如果查询大量数据的时候,我们往往使用分页进行查询,也就是每次处理小部分数据,这样对数据库压力就在可控范围内。

SELECT * from user limit startIndex,pageSize 
//    分页
    List<User> getUserByLimit(Map<String , Integer> map);
<?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.zs.mapper.UserMapper">

    <!--结果集映射-->
    <resultMap id="UserMap" type="user">
        <!--column数据库中的字段,property实体类中的属性-->
        <result column="id" property="id"></result>
        <result column="name" property="name"></result>
        <result column="pwd" property="password"></result>
    </resultMap>

    <select id="getUserByLimit" parameterType="map" resultMap="UserMap">
        SELECT * FROM mybatis_user LIMIT #{startIndex},#{pageSize}
    </select>
</mapper>
    @Test
    public void getUserByLimit() {
        try (SqlSession sqlSesion = MyBatisUtils.getSqlSesion();){
            UserMapper mapper = sqlSesion.getMapper(UserMapper.class);
            Map<String, Integer> map = new HashMap<>();
            map.put("startIndex",0);
            map.put("pageSize",2);
            List<User> userList = mapper.getUserByLimit(map);
            System.out.println(userList);
        }
    }

2 利用注解开发

1、我们在我们的接口中添加注解

    //根据查询全部用户
    @Select("select * from user")
    List<User> getUsers();

2、在mybatis的核心配置文件中注入

<!--    绑定接口-->
    <mappers>
        <mapper class="com.xxxx.dao.UserMapper"/>
    </mappers>

3、我们去进行测试

 @Test
   public  void test(){
       try(SqlSession sqlSession = MyBatisUtils.getSqlSesion();){
           UserMapper mapper = sqlSession.getMapper(UserMapper.class);
           List<User> users = mapper.getUsers();
           for (User user:users) {
               System.out.println(user);
           }
       }
   }

自动提交事务:
在这里插入图片描述

public interface UserMapper {
    //根据查询全部用户
    @Select("select * from user")
    List<User> getUsers();

//    方法存在多个参数,所有的参数前面必须加上@Param
    @Select("select * from user where id = #{id}")
    User getUserById(@Param("id") int id );

    @Insert("insert into user(id,name,pwd) values(#{id},#{name},#{pwd})")
    int addUser(User user);

    @Update("update user set name = #{name} , pwd = #{pwd} where id = #{id}")
    int updateUser(User user);

    @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid") int id);
}

一定要注意:将接口注册绑定到我们的核心配置文件中:

<!--    绑定接口-->
    <mappers>
        <mapper class="com.xxxx.dao.UserMapper"/>
    </mappers>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值