mybatis 学习笔记1

pom.xml添加依赖


            org.mybatis
            mybatis
            3.4.4

我们创建一张user表
CREATE TABLE user (
  id int(11) NOT NULL AUTO_INCREMENT,
  name char(30) NOT NULL,
  age int(4) NOT NULL,
  sex int(4) NOT NULL,
  PRIMARY KEY (id)
)

创建mybats配置文件mybatis_config.xml




    
        
            
            
                
                
                
                
            

        
    

    
        
    


创建mapper映射器userMapper.xml


    
    
        insert into user(name,sex,age) VALUES (#{name},#{sex},#{age})
    

在userMapper.xml中我们定义了一个select元素,返回一个user类型的对象。接下来我们实现相应的userMappper和user类。
首先我们定义userMapper,userMapper定义为一个接口

public interface UserMapper {
    User selectUserByName(String name);
    void insertUser(User user);
}

该接口定义了一个selectUser方法,和select元素相匹配。
接下来我们实现User类。

public class User {
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    private String name;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getSex() {
        return sex;
    }

    public void setSex(int sex) {
        this.sex = sex;
    }

    private int age;
    private int sex;

    @Override
    public String toString() {
        return "username is "+name + " age is "+age;
    }
}

User类定义了name,age,sex属性。

接下来我们编写测试程序从mysql中查询数据映射到我们的User对象中。

public class TestUser {

    public SqlSessionFactory getSessionFactory(){
        SqlSessionFactory sqlSessionFactory = null;
        try {
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        }catch (IOException ex){

        }
        return sqlSessionFactory;
    }
    @Test
    public void selectUserByID(){
        SqlSessionFactory sqlSessionFactory = getSessionFactory();
        SqlSession session = sqlSessionFactory.openSession();

        try {
            UserMapper userMapper = (UserMapper)session.getMapper(UserMapper.class);

            User user1 = new User();
            user1.setName("jack");
            user1.setAge(20);
            user1.setSex(1);
            userMapper.insertUser(user1);

            User user = userMapper.selectUserByName("jack");
            System.out.println(user.toString());
            Assert.assertNotNull(user);
        }catch (Exception ex){
            ex.printStackTrace();

        }finally {
            session.close();
        }

    }


}

首先读取mybatis-config.xml,然后构造sqlSessionFactory实例。使用sqlSessionFactory创建会话,使用会话获取mapper映射器UserMapper,调用selectUser方法触发sql查询返回User对象。

你可能感兴趣的:(mybatis 学习笔记1)