注册 登录
编程论坛 J2EE论坛

mapper编程基本思想

fyzn12 发布于 2019-09-25 08:56, 6115 次点击
---
title: mapper接口编程
date: 2019-09-24
lastmod: 2019-09-24
author: fyzn
categories: ["SSM—Mybatis"]
tags: ["mybatis"]
---
##面向接口编程的思路  
1. 创建pojo(javaBean)类   
2. 创建接口  
3. 创建接口对应的mapper文件   
   注意:  
 1)mapper文件名必须和接口名相同,如接口名为ITeacher则mapper名为ITeacher(并且在同一个包下,实践得到),如果使用扫描包的方式,那么两者必须在同一个包下,如  

     <!-- mapper接口方式加载mapper文件 -->
          <mappers>
                <package name="com.dao"/>
          </mappers>  
      
 如果用读取文件的方式,则不用在同一个包下如下  

    <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.方法读取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();
    }
&emsp;  
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;
        }
    }  
&emsp;   
 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>
 
 原文来自本人github fyzn12.
4 回复
#2
fyzn122019-09-25 09:57
本文章仅属于个人理解,如果那位大神有不同的见解,求评论
#3
林月儿2019-09-25 19:42
#4
fyzn122019-09-26 20:59
该文章仅属个人观点,若那位大神有不同的见解,或者文章有误,请告知,谢谢!
#5
fyzn122019-10-16 10:54
该文章仅属个人观点,若那位大神有不同的见解,或者文章有误,请告知,谢谢!
1