mybatis注解开发-@Select注解 执行根据id查询一条记录,模糊查询,查询count()

概述

本文介绍根据id查询一条记录,模糊查询,查询count()函数

根据id查询一条记录

修改IUserMapper

增加下面代码:

@Select("select id,username,password,age,sex,status from user where id=#{id}")
public User queryById(String id);

注解中的sql语句,与 mapper.xml 中的写法是一样的

由于只传入 一个基本数据类型,所以在sql中 #{id}可以写成任意值,如:#{aaa}也是可以的,但代码规范不允许这么写

测试

@org.junit.Test
public void test3() throws IOException {

    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);

    User u=mapper.queryById("10001");
    String info = String.format("id:%s,用户名:%s", u.getId(), u.getUsername());
    System.out.println(info);

    sqlSession.close();
    inputStream.close();
}

模糊查询

修改IUserMapper

增加下面代码:

@Select("select id,username,password,age,sex,status from user where username like #{username}")
public List<User> queryByName(String username);

测试

@org.junit.Test
public void test5() throws IOException {

    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);

    List<User> list=mapper.queryByName("李%");
    for(User u:list) {

        String info = String.format("id:%s,用户名:%s", u.getId(), u.getUsername());
        System.out.println(info);
    }

    sqlSession.close();
    inputStream.close();
}

查询count()

修改IUserMapper

增加下面代码:

@Select("select count(id) from user where sex = #{sex}")
public int queryCountBySex(String sex);

由于查询 count() 函数,所有返回 int 型

测试

@org.junit.Test
public void test6() throws IOException {

    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    SqlSession sqlSession = sqlSessionFactory.openSession();
    IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);

    int count=mapper.queryCountBySex("1");
    System.out.println("男生有"+count+"人!");

    sqlSession.close();
    inputStream.close();
}

原文出处:/show_1IXlfNj48o.html