mybatis 查询聚合函数(select)

上接:mybatis 创建maven工程

概述

查询User表有多少个用户

修改 IUserMapper

增加下面代码:

public int selectCount();

完整代码

package org.malaoshi.mapper;

import org.malaoshi.entity.User;

import java.util.List;

public interface IUserMapper {

    public List<User> selectAll();

    public int save(User user);

    public int updateById(User user);

    public int deleteById(String id);

    public User selectById(String id);

    public List<User> selectByUsername(String username);

    public int selectCount();
}

修改 userMapper.xml

增加下面标签:

<select id="selectCount" resultType="int">
    select count(id) from user
</select>

解释:

  • resultType属性:查询出来的结果是int型,必须加,否则报错

完整代码如下

<?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">

<!-- namespace名字必须与dao包路径接口名完全相同 -->
<mapper namespace="org.malaoshi.mapper.IUserMapper" >

    <!-- id名必须与dao中的方法名相同 -->
    <select id="selectAll" resultType="org.malaoshi.entity.User">
        select id,username,password from user
    </select>

    <insert id="save" parameterType="org.malaoshi.entity.User">
        insert into user (id,username,password) values (#{id},#{username},#{password})
    </insert>

    <update id="updateById" parameterType="org.malaoshi.entity.User">
        update user set username=#{username},password=#{password} where id=#{id}
    </update>

    <delete id="deleteById" >
        delete from user where id=#{id}
    </delete>

    <select id="selectById" resultType="org.malaoshi.entity.User">
        select id,username,password from user where id=#{id}
    </select>

    <select id="selectByUsername" resultType="org.malaoshi.entity.User">
        select id,username,password from user where username like #{username}
    </select>

    <select id="selectCount" resultType="int">
        select count(id) from user
    </select>
</mapper>

执行

@Test
public void testSelectCount() throws IOException {
/*
 1. 读取  mybatis-config.xml 自定义命名的全局配置文件.
    getResourceAsStream 使用的资源路径
 */
    InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
    // 2. 使用sqlSession的工厂构造器来读入全局配置,再生成一个sqlSession工厂.
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    // 3. 通过 sqlSession 工厂打开一个 sqlSession
    SqlSession sqlSession = sqlSessionFactory.openSession();
    //4 使用SqlSession创建Dao接口的代理对象
    IUserMapper mapper = sqlSession.getMapper(IUserMapper.class);

    int count=mapper.selectCount();
    System.out.println("总共记录数:"+count);
    sqlSession.close();
    inputStream.close();
}

原文出处:/show_1EF6WOYFbbLi.html