实现步骤:
1、基础环境:和基础方式一样,先配置mybatis环境,mysql驱动,conf.xml、mapper.xml
2、(不同之处)
约定的目标:省略statement,即根据约定直接可以定位出SQL语句,基于
a、接口开发(mybatis基于接口开发,所以先新建一个接口(interface))StudentMapper.java——操作mabatis的接口,该接口中必须遵循以下约定
1、方法名和StudentMapper.xml文件中标签的id相同
2、方法的输入参数和StudentMapper.xml中的标签参数类型parameterType一致
3、返回值就是StudentMapper.xml中的返回类型resultType也一样
接口与StudentMapper.xml的联系如下
StudentMapper.xml中的方法
除了以上约定,要实现接口中的方法与Mapper.xml中的SQL标签一一对应,还需要1点:
namespace的值要等于接口的全类名——其实就是把他们放在同一个资源目录下,命名也相同,只不过一个是StudentMapper.xml,另一个是StudentMapper.java。
匹配过程(即约定的过程,前提是满足前面的约定):
1、根据 接口名(StudentMapper) 找StudentMapper.xml文件(依据:namespace=接口全类名)
2、根据 接口的方法名找到StudentMapper.xml文件中的SQL标签(方法名=SQL标签Id值)
以上两点可以保证:当我们调用接口的方法时,程序能够自动定位到某一个Mapper文件中的SQL标签。总的来说就是只要约定是满足的,就不会因为其他接口有同样的方法而找错。
习惯:SQL映射文件(mapper.xml)和 接口(interface)放在同一个包中
注意:修改config.xml加载文件的路径
执行:
StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);//操作哪 个方法就写哪个接口.class(反射)
Student stu = stuMapper.xxx方法();//接口中的方法,程序自动找到SQL语句
附代码结构:
案例工程结构:
其实和基础方式没有太大区别,就是将各个文件放在不同的包中方便管理
1、config.xml
和基础方式基本是一样的,就是最后要该对应的路径不再赘述
2、MyTestMybatis.java
package com.sicnu.test;
import java.io.IOException;
import java.io.Reader;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import com.sicnu.sty.Student;
import com.sicnu.sty.mapper.StudentMapper;
public class MyTestMybatis {
public static void queryStudentByID() throws IOException{
// 将配置文件变为流的形式
Reader reader = Resources.getResourceAsReader("conf.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
SqlSession sqlSession = sqlSessionFactory.openSession();
// 根据namespace+id找到想要的查询语句
// 1、基础方法很复杂,要写namespace+id才能找到对应的SQL语句
/*String statement = "com.sicnu.sty.StudentMapper.queryStudentByID";*/
// 2、约定不需要statement,默认的方式
//动态代理
StudentMapper stuMapper = sqlSession.getMapper(StudentMapper.class);//,操作是哪个接口就写哪个接口反射
Student stu = stuMapper.queryStudentByID(1);//接口中的方法,程序自动找到SQL语句
System.out.println("stu:"+stu);
sqlSession.close();
}
public static void main(String[] args) throws IOException {
queryStudentByID();
}
}
3、StudentMapper.java接口
package com.sicnu.sty.mapper;
import com.sicnu.sty.Student;
//
public interface StudentMapper {
/*
* 1、方法名和StudentMapper.xml文件中标签的id相同
* 2、方法的输入参数和StudentMapper.xml中的标签参数类型parameterType一致
* 3、返回值就是StudentMapper.xml中的返回类型resultType也一样
*/
public Student queryStudentByID(int id);
}
其他代码与基础方式一样的
最后附上结果: