mybatis 根据id查询一条记录(select)

修改 IUserMapper

增加selectById方法

public User selectById(String id);

解释:

  • 形参 String id:传入id,根据id查询
  • 返回 User 类型,由于是根据注解 id 查询,最多只能查询出1条记录,所以返回 User,不需要返回 List 类型

完整代码

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);
}

修改 userMapper.xml

增加select标签,根据id查询记录

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

解释:

  • 不需要parameterType属性,因为传入的是 java基本数据类型
  • #{id}:传入的值。由于只传入一个值,此处可以随意起名
  • resultType属性:查询出来的结果,封装到User类对象中

完整代码如下

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

</mapper>

执行

@Test
public void testSelectById() 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);

    if(user!=null) {
        String info = String.format("id:%s,用户名:%s,密码:%s", user.getId(), user.getUsername(), user.getPassword());
        System.out.println(info);
    }else{
        System.out.println("没有查询到数据!");
    }
    System.out.println(info);
    sqlSession.close();
    inputStream.close();
}

原文出处:/show_1EF6WNo03wZe.html