面向接口编程的思路

  1. 创建pojo(javaBean)类
  2. 创建接口
  3. 创建接口对应的mapper文件
    注意:
    1)mapper文件名必须和接口名相同,如接口名为ITeacher则mapper名为ITeacher(并且在同一个包下,实践得到),如果使用扫描包的方式,那么两者必须在同一个包下,如

如果用读取文件的方式,则不用在同一个包下如下

<mappers>
    <mapper resource="mapper/*.xml"/>
</mappers>

2)mapper文件的namespace取值必须和接口的全路径相同
3)mapper中的SQL声明的id必须和接口中的方法名相同,如接口中声明方法seleteAll则sql的id必须为seleteAll
4)多参传递可以不写parameterType属性
5)参数的下标书写 <selete * from teacher where name=#{0} and age=#{1}表示方法中传的参数的第一个参数和第二个参数
6)参数的占位书写
7)参数的声明书写 方法中用@Param声明。
4. 读取mybatis-config.xml文件获取数据库的连接,以及读取mapper文件,得到InputStream对象,创建SqlSessionFactory对象,利用SqlSessionFactory对象建立session连接通过openSession()方法

InputStream is;
try {
    //1.利用org.apache.ibatis.io.Resources方法读取mybatis-config.xml
    is = Resources.getResourceAsStream("mybatis-config.xml");
    // 2.通过文件流,创建一个sqlSessionFactory
    SqlSessionFactory factory = new SqlSessionFactoryBuilder()
            .build(is);
    // 3.通过工厂创建一个数据库的连接session
    session = factory.openSession();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}


5. 编写service业务逻辑,通过session.getMapper(T.class)获取接口声明(在spring后,可以直接用@Resource或则@Autowired注解映射Bean)实例代码如下:

 @Override
public List<StudentCourse> list(Map<String, Object> map) {
    if (session !=null) {
        studentDao = session.getMapper(StudentDao.class);//获取相应的接口
        return studentDao.list(map);
    }else{
        return null;
    }
}  


6. 试图层的调用
7. 动态sql编程,在mapper文件中编写sql语句存在一定的逻辑性

<select id="seleteDy" resultType="teacher">
     selete * from teacher
        --where 1=1 <!--保证where以前的语句能执行 --> 
      <where>
         <if test="name !=null and name !=''">
              name=#{name}
         </if>
         <if test="age !=null and age !=''">
              age=#{age}
         </if>
      </where>
</select>