MyBatis 详解(五)

发布于 2021-07-26  93 次阅读


分页

sql 语句使用 limit 关键字

<select id="getUserByLimit" parameterType="map" resultType="ml.guest997.pojo.User">
    select * from mybatis.user limit #{startIndex},#{pageSize}
</select>
//分页查询
List<User> getUserByLimit(Map<String, Integer> map);
@Test
public void getUserByLimitTest() {
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    Map<String, Integer> map = new HashMap<>();
    map.put("startIndex", 0);
    map.put("pageSize", 3);
    List<User> userList = userMapper.getUserByLimit(map);
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}
/*结果为
User{id=1, name='Guest997', pwd='123456'}
User{id=2, name='GUEST997', pwd='123456'}
User{id=3, name='guest997', pwd='123456'}
*/

PageHelper 插件

<!--pagehelper 插件依赖-->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.2.0</version>
</dependency>
<!--mybatis-config.xml-->
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor">
        <!--分页参数合理化,如果 pageNum<1 会查询第一页,如果 pageNum>pages 会查询最后一页-->
        <property name="reasonable" value="true"/>
    </plugin>
</plugins>
//插件分页查询
List<User> getUserByPageHelper();
<select id="getUserByPageHelper" resultType="ml.guest997.pojo.User">
    select * from mybatis.user
</select>
@Test
public void getUserByPageHelper(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
    PageHelper.startPage(1, 3);      //页数,页面容量
    List<User> userList = userMapper.getUserByPageHelper();
    for (User user : userList) {
        System.out.println(user);
    }
    sqlSession.close();
}

注解实现 CRUD

映射的语句可以不用 XML 来配置,而可以使用 Java 注解来配置。使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 sql 语句更加混乱不堪。 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。

修改 MyBatisUtil 文件

public static SqlSession getSqlSession(){
    //自动提交事务
    return sqlSessionFactory.openSession(true);
}

编写代码

package ml.guest997.mapper;

import ml.guest997.pojo.User;
import org.apache.ibatis.annotations.*;
import java.util.List;
import java.util.Map;

public interface UserMapper02 {

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

    @Delete("delete from user where id = #{uid}")
    int deleteUser(@Param("uid") int id);    //方法中的基本数据类型参数都使用 @Param 注解提高可读性,sql 语句引用的参数就是注解中的参数,故参数名一定要相同。

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

    @Select("select * from user where binary name = #{name} and pwd = #{pwd}")
    List<User> getUser(Map<String, String> map);

}

使用 class 属性绑定接口

<mappers>
    <mapper class="ml.guest997.mapper.UserMapper02"/>
</mappers>

测试

package ml.guest997.mapper;

import ml.guest997.pojo.User;
import ml.guest997.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UserMapper0Test {

    @Test
    public void addUser(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserMapper02 userMapper02 = sqlSession.getMapper(UserMapper02.class);
        int result = userMapper02.addUser(new User(5, "test02", "123456"));
        if (result > 0){
            System.out.println("插入成功!");
        } else {
            System.out.println("插入失败!");
        }
        sqlSession.close();
    }
    @Test
    public void deleteUser(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserMapper02 userMapper02 = sqlSession.getMapper(UserMapper02.class);
        int result = userMapper02.deleteUser(5);
        if (result > 0){
            System.out.println("删除成功!");
        } else {
            System.out.println("删除失败!");
        }
        sqlSession.close();
    }
    @Test
    public void updateUser(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserMapper02 userMapper02 = sqlSession.getMapper(UserMapper02.class);
        int result = userMapper02.updateUser(new User(5, "zyp997", "666666"));
        if (result > 0){
            System.out.println("修改成功!");
        } else {
            System.out.println("修改失败!");
        }
        sqlSession.close();
    }
    @Test
    public void getUser(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserMapper02 userMapper02 = sqlSession.getMapper(UserMapper02.class);
        Map<String, String> map = new HashMap<>();
        map.put("name","guest997");
        map.put("pwd","123456");
        List<User> userList = userMapper02.getUser(map);
        for (User user : userList) {
            System.out.println(user);
        }
    }

}