Mybatis之Mapper动态代理方式

目录

一、 Mapper动态代理

二.、Mapper动态代理规范

三、Mapper.xml映射文件

1.在src目录下创建mapper文件,在mapper文件下定义mapper接口

2、在StudentMapper接口中编写方法

3、Mapper.xml(映射文件)

四、测试




的Mapper动态代理开发规范

Mapper接口开发方法只需要程序员编写Mapper接口(相当于Dao接口),由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同上边Dao接口实现类方法。

一、 Mapper动态代理

​ mapper不使用动态代理是指dao层的实现自己创建,在接口实现类的方法中自己调用SqlSession完成对数据库的操作,这样只能向SQL中传递一个参数,多个参数要封装到POJO或者Map中,且调用SqlSession对象的方法时会有硬编码现象namespace+id
​ 使用Mapper动态代理只需要写dao层接口,不需要创建dao层实现类,Mybatis会自动生成实现类的代理对象。在dao层只需要创建接口与映射文件即可

二.、Mapper动态代理规范

  • 接口名称需要与映射文件名称相同
  • 映射配置文件中namespace必须是接口的全名
  • 接口中的方法名和映射配置文件中的标签的id一致
  • 接口中的返回值类型和映射配置文件中的resultType的指定类型一致

三、Mapper.xml映射文件

1.在src目录下创建mapper文件,在mapper文件下定义mapper接口

Mybatis之Mapper动态代理方式_第1张图片

2、在StudentMapper接口中编写方法

public interface StudentMapper {
    public Student findStudentById(int id);
}

3、Mapper.xml(映射文件)

定义mapper映射文件StudentMapper.xml(内容同Student.xml),需要修改namespace的值为 StudentMapper接口路径。将StudentMapper.xml放在classpath 下mapper目录 下。




    
}

四、测试

创建一个测试类(TestDemo.java)

public class TestDemo {
    SqlSessionFactory ssf = null;
    @Before
    public void creatFactory(){
        InputStream input = null;
        try {
            input = Resources.getResourceAsStream("SqlMapConfig.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        ssf = new SqlSessionFactoryBuilder().build(input);
    }
    @Test
    public void testMapper(){
        //获取session
        SqlSession sqlSession = ssf.openSession();
        //获取mapper接口的代理对象
        StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        //调用代理对象方法
        Student student = mapper.findStudentById(5);
       System.out.println(student.getStudentName());
        session.commit();
        //关闭session
        session.close();

    }
}

你可能感兴趣的:(mybatis,java,数据库,tomcat,idea,大数据)