Mybatis注解开发---增删改查

目录

(1)insert测试方法

(2)delete测试方法

(3)update测试方法

(4)select测试方法 


一定要记得注册映射


        
    
public interface UserMapper {
    @Select("select *from user")
    List findAll();
    //添加用户
    @Insert("insert into user(username,sex,address) values(#{username},#{sex},#{address})")
    void add(User user);
    //删除用户,根据id
    @Delete("delete from user where id=#{id}")
    void delete(int id);
    //修改用户
    @Update("update user set username=#{username},sex=#{sex},address=#{address} where id=#{id}")
    void update(User user);
}

(1)insert测试方法

 @Test
    public void Test2() throws Exception {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper=session.getMapper(UserMapper.class);
        List userList=userMapper.findAll();
        userList.forEach(System.out::println);
        session.commit();
        session.close();
        is.close();
    }

(2)delete测试方法

@Test
    public void Test3() throws Exception {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper=session.getMapper(UserMapper.class);
        User user=new User("洒洒水","男","厦门");
        userMapper.add(user);
        session.commit();
        session.close();
        is.close();
    }

(3)update测试方法

 @Test
    public void Test4() throws Exception {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper=session.getMapper(UserMapper.class);
        userMapper.delete(16);
        session.commit();
        session.close();
        is.close();
    }

(4)select测试方法 

 @Test
    public void Test5() throws Exception {
        InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        SqlSession session = sqlSessionFactory.openSession();
        UserMapper userMapper=session.getMapper(UserMapper.class);
        User user=new User(17,"大大","女","北京");
        userMapper.update(user);
        session.commit();
        session.close();
        is.close();
    }

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