Mybatis根据id查询用户信息

User.java  存储用户的信息
User.xml   配置查询用户的sql语句
SqlMapConfig.xml    加载配置文件,
MybatisFirst.java   数据库操作文件

MybatisFirst.java
public class MybatisFirst {
    //根据id查询用户信息,得到一条记录结果
    @Test
    public void findUserByIdTest() throws IOException{
        //MyBatis配置文件
        String resource = "SqlMapConfig.xml";
        //得到配置文件流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        
        //创建会话工厂,想build中传入配置文件信息
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        //通过工厂得到SqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //通过SqlSession操作数据库
        User user = sqlSession.selectOne("test.findUserById", 16);
        
        System.out.println(user);
        
        try{
            sqlSession.close();
        } catch(Exception e) {
            throw new RuntimeException(e);
        }
    }
}

User.java
public class User {
    private int id;
    private String username;//  用户姓名
    private String sex;// 性别
    private Date birthday;// 生日
    private String address;// 地址
    @Override
    public String toString() {
        return "User [id=" + id + ", username=" + username + ", sex=" + sex
                + ", birthday=" + birthday + ", address=" + address + "]";
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    
}


User.xml




    


SqlMapConfig.xml



    
    
        
        
            
        
            
                
                
                
                
            
        
    
    
    
        
    
    


你可能感兴趣的:(java-MyBetis)