MyBatis Mapper动态代理规则及动态代理的调用

1.对应的书写SQL语句的xml文件中的nameapsce必须为接口的全路径

2.接口中的方法名称必须和xml中对应的ID相同

3.xml中的parameterType必须和接口中的参数类型一致          当传递多个参数时parameterType可以省略不写

4.xml中的ResultType必须和接口中的返回值类型一致

例如:对于一个客户表   实现其CRUD

其Customer.xml 如下:




    
    
    
    

    
    

    
    
    
        
        
            select last_insert_id()
        
	  insert into `customer` (cust_name,cust_profession,cust_phone,email)
	  values (#{cust_name},#{cust_profession},#{cust_phone},#{email})
	

    
    
        update `customer` set cust_name=#{cust_name} where cust_id=#{cust_id}
    

    
    
        delete from `customer` where cust_id=#{cust_id}
    

则其对应的接口为:

public interface CustomerMapper {
    //根据id查询客户
    public Customer queryCustomerById(Integer id);
    //查询所有
    public List queryAll();
    //根据用户名模糊查询
    public List queryCustomerByName(String name);
    //添加
    public void insertCustomer(Customer customer);
    //更新
    public void updateCustomer(Customer customer);
    //删除操作
    public void deleteCustomer(Customer customer);
}

这样便可以实现其动态代理 

 

动态代理的调用:

 public void test2(){
        SqlSession sqlSession = MyBatisUtils.openSession();
        CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
        Customer customer = mapper.queryCustomerById(1);
        System.out.println(customer);

        List customers = mapper.queryAll();
        for (Customer customer1 : customers) {
            System.out.println(customer1);
        }

        List customers1 = mapper.queryCustomerByName("%李%");
        for (Customer customer1 : customers1) {
            System.out.println(customer1);
        }
        sqlSession.close();
    }

 

 

你可能感兴趣的:(mybatis)