Mybatis映射文件(1)

mybatis映射文件——增删改查

public interface EmployeeMapper {
    Employee selectById(Integer id);
    void addEmp(Employee employee);
    void updateEmp(Employee employee);
    void deleteEmpById(Integer id);
}

<mapper namespace="dao.EmployeeMapper">
    <select id="selectById" resultType="employee">
        SELECT * FROM t_employee WHERE id = #{id}
    </select>

    <!--parameterType可以省略-->
    <insert id="addEmp" parameterType="bean.Employee">
        INSERT INTO t_employee VALUES (NULL ,#{lastName},#{gender},#{email})
    </insert>

    <update id="updateEmp">
        UPDATE t_employee SET last_name = #{lastName},gender=#{gender},email = #{email} WHERE id=#{id}
    </update>

    <delete id="deleteEmpById">
        DELETE FROM t_employee WHERE id=#{id}
    </delete>
</mapper>

/**
 *1、 mybatis 允许增删改查直接定义一下返回值类型
 *         Long、Integer、Boolean
 *2、我们需要手动提交数据
 *      sqlSessionFactory.openSession()===》手动提交
 *          sqlSessionFactory.openSession(true)===》自动提交
 * @throws IOException
 */
@Test
public void testSelect() throws IOException {
    SqlSession sqlSession = getSqlSession();
    try {
        //3、获取Employee的代理对象——通过sqlSession为接口创建一个代理对象
        EmployeeMapper mapper = sqlSession.getMapper(EmployeeMapper.class);
        //增删改查
        mapper.addEmp(new Employee(null, "haha", "1", "haha@qq.com"));

        mapper.deleteEmpById(3);

        mapper.updateEmp(new Employee(1, "tona", "1", "toma@qq.com"));

        Employee e = mapper.selectById(2);

        System.out.println(e);
    } finally {
        //4、关闭SqlSession对象
        sqlSession.close();
    }
}

获取自增主键值的策略

自增的数据库:MySQL

<!--
parameterType可以省略
mybatis支持自增主键、自增主键的获取,mabatis也是利用statement.getGenereatedKeys()
useGeneratedKeys="true"使用主键自增获取主键值策略
keyProperty:指定对应的主键属性,也就是mybatis获取到主键后,将这个值封装给JavaBean的那个属性
-->
<insert id="addEmp" parameterType="bean.Employee" useGeneratedKeys="true" keyProperty="id">
    INSERT INTO t_employee(last_name, gender, email) VALUES (#{lastName},#{gender},#{email})
</insert>
非自增的数据库:如Oracle

<!--oracle数据库不支持自增-->
<!--使用Oracle-->
<insert id="addEmp" parameterType="bean.Employee" databaseId="oracle">
    /*
    查询主键的sql语句
    keyProperty:查出主键封装给javaBean的那个属性
    order="BEFORE":当前sql在插入sql之前运行
           AFTER:当前sql在插入sql之后运行
    resultType:查询出的数据的返回值类型
    */
    <selectKey keyProperty="id" order="BEFORE" resultType="Integer">
        SELECT EMPLOYEES_SEQ.nextval FROM dual
    </selectKey>
    INSERT INTO t_employee(EMPLOYEE_ID,last_name, gender, email) VALUES (#{id},#{lastName},#{gender},#{email})
</insert>
mybatis参数处理

单个参数:mybatis不会做任何处理

               #{参数名}:取出参数的值

多个参数:mybatis会做特殊处理

                多个参数会被封装成一个map

                key:param1,。。。。,paramN或者参数的索引也可以

                value:传入的参数值

                #{ }就是从map中获取指定的key值

Employee selectByIdAndLastName(Integer id,String lastNae);
<select id="selectByIdAndLastName" resultType="employee">
    SELECT * FROM t_employee WHERE id = #{id} AND last_name=#{lastName}
</select>
出现异常: org.apache.ibatis.binding.BindingException: Parameter 'id' not found. Available parameters are [arg1, arg0, param1, param2]


改成:

<select id="selectByIdAndLastName" resultType="employee">
    SELECT * FROM t_employee WHERE id = #{param1} AND last_name=#{param2}
</select>

程序运行OK。

推荐:

命名参数:明确指定封装参数时的map的key:

@Param("id")

多个参数会被封装成一个map

        key:使用@Param注解指定的值

        value:参数值

#{ }取出对应的参数值

Employee selectByIdAndLastName(@Param("id") Integer id,@Param("lastName") String lastName);
<select id="selectByIdAndLastName" resultType="employee">
    SELECT * FROM t_employee WHERE id = #{id} AND last_name=#{lastName}
</select>

POJO:

如果多个参数正好时我们业务逻辑的数据模型,我们可以直接传入pojo

        #{属性名}:取出传入的pojo的属性值

Map:

如果多个参数不是业务模型中的数据,没有对应的pojo,不经常使用,为了方便,我们也可以传入map

        #{key}:取出map对应的值

TO:

如果多个参数不是业务模型中的数据,但是经常要使用,推荐来编写一个TO(Transfer Object)数据传输对象

Page{

int index;

int size;

}

============小结==============

Employee getEmp(@Param("id") Integer id,String lastName);
取值:id==》#{id/param1}  lastName==》#{param2}
Employee getEmp(@Param("id") Integer id,@Param("e") Employee emp);
取值:id==》#{param1}  lastName==》#{param2.lastName/e.lastName}
###特别注意:如果是Collection(List,Set)类型或者是数组,也会特殊处理。也是把传入的list或数组封装在map中
key:Collection(collection),如果是List还可以使用key(list),数组(array)
Employee getEmpById(List<Integer> ids);
取值:取出第一个值id==》#{ids[0]}  

==============源码——mybatis对参数的处理==============

public class ParamNameResolver {
    private static final String GENERIC_NAME_PREFIX = "param";
    /**
     * 存放参数个数
     */
    private final SortedMap<Integer, String> names;

    private boolean hasParamAnnotation;
    //解析参数封装成map
    public ParamNameResolver(Configuration config, Method method) {
        final Class<?>[] paramTypes = method.getParameterTypes();
        final Annotation[][] paramAnnotations = method.getParameterAnnotations();
        final SortedMap<Integer, String> map = new TreeMap<Integer, String>();
        int paramCount = paramAnnotations.length;
        // get names from @Param annotations
        //索引参数
        for (int paramIndex = 0; paramIndex < paramCount; paramIndex++) {
            if (isSpecialParameter(paramTypes[paramIndex])) {
                // skip special parameters
                continue;
            }
            String name = null;
            //如果当前参数的注解为@Param注解
            for (Annotation annotation : paramAnnotations[paramIndex]) {
                if (annotation instanceof Param) {
                    hasParamAnnotation = true;
                    name = ((Param) annotation).value();//获取参数的值
                    break;
                }
            }
            if (name == null) {
                // @Param was not specified.
                if (config.isUseActualParamName()) {
                    name = getActualParamName(method, paramIndex);
                }
                if (name == null) {
                    // use the parameter index as the name ("0", "1", ...)
                    // gcode issue #71
                    name = String.valueOf(map.size());//如果么有标注解就是map
                }
            }
            map.put(paramIndex, name);//放入
        }
        names = Collections.unmodifiableSortedMap(map);
    }

    private String getActualParamName(Method method, int paramIndex) {
        if (Jdk.parameterExists) {
            return ParamNameUtil.getParamNames(method).get(paramIndex);
        }
        return null;
    }

    private static boolean isSpecialParameter(Class<?> clazz) {
        return RowBounds.class.isAssignableFrom(clazz) || ResultHandler.class.isAssignableFrom(clazz);
    }

    /**
     * Returns parameter names referenced by SQL providers.
     */
    public String[] getNames() {
        return names.values().toArray(new String[0]);
    }

    /**
     *  names (param1, param2,...).
     * </p>
     */
    public Object getNamedParams(Object[] args) {
        final int paramCount = names.size();//获取参数个数
        if (args == null || paramCount == 0) {
            return null;//参数为null直接返回
            //如果只有一个元素,并且没有param注解,直接返回args[0],单个元素直接返回
        } else if (!hasParamAnnotation && paramCount == 1) {
            return args[names.firstKey()];
        } else {
            final Map<String, Object> param = new ParamMap<Object>();
            int i = 0;
            //给上面新建的param这个map保存数据——遍历names集合
            for (Map.Entry<Integer, String> entry : names.entrySet()) {
                //names集合的value值作为key,names集合的key又作为取值的参考
                //如:names集合{0=id,1=lastName}===》{id=args[0]:1,lastName=args[1]:toma}
                param.put(entry.getValue(), args[entry.getKey()]);
                // add generic param names (param1, param2, ...)
                //额外的将每个参数保存到map中,使用新的key:param1,param2。。。。paramN
                final String genericParamName = GENERIC_NAME_PREFIX + String.valueOf(i + 1);
                // ensure not to overwrite parameter named with @Param
                if (!names.containsValue(genericParamName)) {
                    param.put(genericParamName, args[entry.getKey()]);
                }
                i++;
            }
            return param;
        }
    }
}

ParamNameResolver解析参数封装map的:

1、names获取参数(0=id,1=lastName)

2、获取每个表了@param注解的参数的值:id、lastName,赋值给name

3、每次解析一个参数给map中保存信息:(key:参数索引,value:name的值)

        name的值:标注了param注解:注解的值

        没有标注:1、全局配置isUseActualParamName(JDK1.8才行):name=参数名

                         2、name=map.size()——相当于当前元素的索引

===============关于参数的获取================

#{ }:可以获取map中的值或者pojo对象中的值

${ }:可以获取map中的值或者pojo对象中的值

        区别:

<select id="selectByIdAndLastName" resultType="employee">
    SELECT * FROM t_employee WHERE id = #{id} AND last_name=#{lastName}
</select>
执行的sql语句为: Preparing: SELECT * FROM t_employee WHERE id = ? AND last_name=?
<select id="selectByIdAndLastName" resultType="employee">
    SELECT * FROM t_employee WHERE id = ${id} AND last_name=#{lastName}
</select>

执行的sql语句为:Preparing: SELECT * FROM t_employee WHERE id = 1 AND last_name=?

#{ }:是以预编译的形式将参数设置到sql语句中,PrepareStatement。防止sql注入

${ }:将取出的值直接拼装在sql中。会有安全问题

大多数情况下,我们取参数的值都应该使用#{ }

但是在原生jdbc不支持占位符的地方就可以使用${ }进行取值

比如:分表:按照年份分表拆分

    select * from ${year}_salary where xxxx

    select * from employ order by ${ name } ${ desc/asc}——排序

#{ }:更丰富的用法:

        规定一些规则:

        javaType、jdbcType、mode(存储过程)、numericScale(小数位数)、

        resultMap(结果集)、 typeHandler(类型处理器)、jdbcTypeName、express

jdbcType:通常需要在某些特定的条件下被设置:在我们数据为null的时候,有些数据库可能不能识别mybatis对null的默认处理,比如oracle(报错)——JdbcType OTHER:无效类型,因为mybatis对所有的null都映射的是原生jdbc的 Other类型

由于全局配置中:jdbcTypeForNull=OTHER,Oracle不支持:——两种解决:

1、#{ 参数,jdbcType=OTHER}     2、在全局配置文件中设置:jdbcTypeForNull=NULL

<setting name="jdbcTypeForNull" value="NULL"></setting>

posted @ 2018-05-21 18:17  惶者  阅读(133)  评论(0编辑  收藏  举报