Mybatis之查询所有数据

查询数据
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">

    <!--查询所有用户-->
    <select id="selectUsersAll" resultType="com.lying.pojo.Users">
        select * from users
    </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 {
     
    List<Users> selectUsersAll() 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 {
     
    /**
     * 查询所有用户
     * @return
     */
    @Override
    public List<Users> selectUsersAll() throws IOException {
     
        //创建SqlSessionFactory对象
        InputStream inputStream=Resources.getResourceAsStream("mybatis-cfg.xml");
        SqlSessionFactory sqlSessionFactory= new SqlSessionFactoryBuilder().build(inputStream);
        //获取SqlSession对象
        SqlSession sqlSession =sqlSessionFactory.openSession();
        //通过SqlSession对象下的API完成对数据库的操作
        List<Users> list=sqlSession.selectList("com.lying.mapper.UserMapper.selectUsersAll");
        //关闭SqlSession对象
        sqlSession.close();
        return list;
    }
}

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();
        List<Users> list=usersDao.selectUsersAll();
        for(Users users:list){
     
            System.out.println(users.getUserid()+"\t"+users.getUsername()+"\t"+users.getUsersex());
        }
    }
}

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