Mybatis根据用户ID查询数据

根据用户ID查询数据
1,修改映射配置文件UsersMapper.xml

<?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.lying.mapper.UserMapper">
    <!--根据用户ID查询用户-->
    <select id="selectUsersById" parameterType="int" resultType="com.lying.pojo.Users" >
        select * from users where userid=#{
     suibian}
    </select>
</mapper>




2,修改UserDao接口
UserDao.java

package com.lying.dao;

import com.lying.pojo.Users;

import java.io.IOException;
import java.util.List;

/**
 * @Author:Lying
 * @Date:2020/8/30
 * @Description:com.lying.dao
 * @version:1.0
 */
public interface UsersDao {
     
    Users selectUsersById(int userid) throws IOException;
}



3,修改UserDao接口实现类
UserDaoImpl.java

package com.lying.dao.com.lying.dao.impl;

import com.lying.dao.UsersDao;
import com.lying.pojo.Users;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * @Author:Lying
 * @Date:2020/8/30
 * @Description:com.lying.dao.com.lying.dao.impl
 * @version:1.0
 */
public class UsersDaoImpl implements UsersDao {
     
    /**
     * 根据用户ID查询用户
     * @param userid
     * @return
     * @throws IOException
     */
    @Override
    public Users selectUsersById(int userid) throws IOException {
     
        //创建SqlSessionFactory对象
        InputStream inputStream=Resources.getResourceAsStream("mybatis-cfg.xml");
        SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象
        SqlSession sqlSession =sqlSessionFactory.openSession();
        Users users=sqlSession.selectOne("com.lying.mapper.UserMapper.selectUsersById",userid);
        sqlSession.close();
        return users;
    }
}

4,修改测试类
Test.java

package com.lying.test;

import com.lying.dao.UsersDao;
import com.lying.dao.com.lying.dao.impl.UsersDaoImpl;
import com.lying.pojo.Users;

import java.io.IOException;
import java.util.List;

/**
 * @Author:Lying
 * @Date:2020/9/1
 * @Description:com.lying.test
 * @version:1.0
 */
public class Test {
     
    public static void main(String[] args) throws IOException {
     
        UsersDao usersDao=new UsersDaoImpl();
        Users users=usersDao.selectUsersById(1);
        System.out.println(users.getUserid()+"\t"+users.getUsername()+"\t"+users.getUsersex());
    }
}

你可能感兴趣的:(Mybatis,java,mybatis,java)