Mybatis学习(1)—— SQL映射

1. 是什么?

MyBatis是一款支持普通SQL查询、存储过程和高级映射持久层框架。MyBatis消除了几乎全部的JDBC代码、参数的设置和结果集的检索。MyBatis可使用简单的XML或注解用于参数配置和原始映射,将接口和Java POJO(普通Java对象)映射成数据库中的记录。html

2. SQL映射

Mybatis能够把Mapper.xml文件直接映射到对应的接口,调用接口方法会自动去Mapper.xml文件中找到对应的标签,这个功能就是利用java的动态代理在binding包中实现的java

2.1 SQL映射配置文件解析

如下面的配置文件为例:sql

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.xrq.StudentMapper">
    <select id="selectStudentById" parameterType="int" resultType="Student">
        <![CDATA[
            select * from student where studentId = #{id}
        ]]>
    </select>
</mapper>数据库

使用<![CDATA[ ... ]]>,能够保证不管如何<![CDATA[ ... ]]>里面的内容都会被解析成SQL语句。所以,建议每一条SQL语句都使用<![CDATA[ ... ]]>包含起来,这也是一种规避错误的作法。缓存

2.1.1 select

2.1.1.1 多条件查询查一个结果

<select id="selectStudentById" parameterType="int" resultType="Student">
        <![CDATA[
            select * from student where studentId = #{id}
        ]]>
</select>mybatis

resultType只能是一个实体类,参数要和实体类里面定义的同样,好比studentId、studentName,MyBatis将会自动查找这些属性,而后将它们的值传递到预处理语句的参数中去。 app

使用参数的时候使用了”#”,另外还有一个符号”$”也能够引用参数,使用”#”最重要的做用就是防止SQL注入框架

调用该语句的Java代码的写法:fetch

public Student selectStudentByIdAndName(int studentId, String studentName)
{
    SqlSession ss = ssf.openSession();
    Student student = null;
    try
    {
        student = ss.selectOne("com.xrq.StudentMapper.selectStudentByIdAndName", 
                new Student(studentId, studentName, 0, null));
    }
    finally
    {
        ss.close();
    }
    return student;
}ui

2.1.1.2 查询多个结果

<select id="selectAll" parameterType="int" resultType="Student" flushCache="false" useCache="true" timeout="10000" fetchSize="100" statementType="PREPARED" resultSetType="FORWARD_ONLY">
    <![CDATA[
        select * from student where studentId > #{id};
    ]]>
</select>

属性的做用:

  • id—-用来和namespace惟一肯定一条引用的SQL语句

  • parameterType—-参数类型,若是SQL语句中的动态参数只有一个,这个属性无关紧要

  • resultType—-结果类型,注意若是返回结果是集合,应该是集合所包含的类型,而不是集合自己

  • flushCache—-将其设置为true,不管语句何时被调用,都会致使缓存被清空,默认值为false

  • useCache—-将其设置为true,将会致使本条语句的结果被缓存,默认值为true

  • timeout—-这个设置驱动程序等待数据库返回请求结果,并抛出异常事件的最大等待值,默认这个参数是不设置的(即由驱动自行处理)

  • fetchSize—-这是设置驱动程序每次批量返回结果的行数,默认不设置(即由驱动自行处理)

  • statementType—-STATEMENT、PREPARED或CALLABLE的一种,这会让MyBatis选择使用Statement、PreparedStatement或CallableStatement,默认值为PREPARED。这个相信大多数朋友本身写JDBC的时候也只用过PreparedStatement

  • resultSetType—-FORWARD_ONLY、SCROLL_SENSITIVE、SCROLL_INSENSITIVE中的一种,默认不设置(即由驱动自行处理)

调用sql语句的Java程序:

public List<Student> selectStudentsById(int studentId)
{
    SqlSession ss = ssf.openSession();
    List<Student> list = null;
    try
    {
        list = ss.selectList("com.xrq.StudentMapper.selectAll", studentId);
    }
    finally
    {
        ss.close();
    }
    return list;
}

2.1.1.3 使用resultMap来接收查询结果

使用resultType的方式是有前提的,那就是假定列名和Java Bean中的属性名存在对应关系,若是名称不对应,可使用resultMap来解决列名不匹配的问题:

<resultMap type="Student" id="studentResultMap">
    <id property="studentId" column="studentId" />
    <result property="studentName" column="studentName" />
    <result property="studentAge" column="studentAge" />
    <result property="studentPhone" column="studentPhone" />
</resultMap>
<select id="selectAll" parameterType="int" resultMap="studentResultMap" flushCache="false" useCache="true"
        timeout="10000" fetchSize="100" statementType="PREPARED" resultSetType="FORWARD_ONLY">
    <![CDATA[
        select * from student where studentId > #{id};
    ]]>
</select>

这样就能够了,注意两点:

一、resultMap定义中主键要使用id

二、resultMap和resultType不能够同时使用

2.1.2 insert

<insert id="insertOneStudent" parameterType="Student">
    <![CDATA[
        insert into student values(null, #{studentName}, #{studentAge}, #{studentPhone});
    ]]>   
</insert>

<insert id="insertOneStudent" parameterType="Student" useGeneratedKeys="true" keyProperty="studentId">
    <![CDATA[
        insert into student(studentName, studentAge, studentPhone) 
            values(#{studentName}, #{studentAge}, #{studentPhone});
    ]]>   
</insert>

useGeneratedKeys表示让数据库自动生成主键,keyProperty表示生成主键的列。

Java调用代码:

public void insertOneStudent(String studentName, int studentAge, String studentPhone)
{
    SqlSession ss = ssf.openSession();
    try
    {
        ss.insert("com.xrq.StudentMapper.insertOneStudent", 
            new Student(0, studentName, studentAge, studentPhone));
        ss.commit();
    }
    catch (Exception e)
    {
        ss.rollback();
    }
    finally
    {
        ss.close();
    }
}

2.1.3 update和delete

update:

<update id="updateStudentAgeById" parameterType="Student">
    <![CDATA[
        update student set studentAge = #{studentAge} where 
            studentId = #{studentId};
    ]]>   
</update>

delete:

<delete id="deleteStudentById" parameterType="int">
    <![CDATA[
        delete from student where studentId = #{studentId};
    ]]>   
</delete>

update的Java代码:

public void updateStudentAgeById(int studentId, int studentAge)
{
    SqlSession ss = ssf.openSession();
    try
    {
        ss.update("com.xrq.StudentMapper.updateStudentAgeById",
                new Student(studentId, null, studentAge, null));
        ss.commit();
    }
    catch (Exception e)
    {
        ss.rollback();
    }
    finally
    {
        ss.close();
    }
}

studentId和studentAge必须是这个顺序,互换位置就更新不了学生的年龄了。

3 Mybatis SQL映射的三种方式

3.1 配置文件

3.1.1 SQL映射文件 XXXmapper.xml

如上面介绍的配置方式:

<mapper namespace="com.test.dao.EmployeeMapper">
    <select id="getEmpById" resultType="com.test.beans.Employee">
        select id,last_name lastName,email,gender from tb1_emplyee where id = #{id}
    </select>
</mapper>

3.1.2 全局配置文件 config.xml

使用Mapper标签进行绑定:

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

3.2 注解方式

定义一个接口:

public interface EmployeeMapperAnnotation {
    @Select("select id,last_name lastName,email,gender from tb1_emplyee where id = #{id}")
    public Employee getEmpById(Integer id);
}

而后在全局配置文件中进行注册:

<mappers>
    <mapper class="com.test.dao.EmployeeMapperAnnotation"></mapper>
</mappers>

3.3 批量注册

<mappers>
        <package name="com.atguigu.mybatis.dao"/>
</mappers>

【注】映射文件名必须和接口同名,而且放在与接口同一目录下,否则注册不了。

以上是简单介绍,具体映射文件的配置见详解Java的MyBatis框架中SQL语句映射部分的编写

4. MyBatis SQL映射的原理

4.1 注册Mapper

Mybatis在初始化时会把获取到的Mapper接口注册到MapperRegistry,注册的时候建立一个Mapper代理工厂,这个工厂经过JDK的代理建立一个执行对象,建立代理须要的InvocationHandler为MapperProxy

//接口注册
public class MapperRegistry {
    public <T> void addMapper(Class<T> type) {
        //若是是接口
        if (type.isInterface()) {
            if (hasMapper(type)) {
                throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
            }
            boolean loadCompleted = false;
            try {
                //放到map中, value为建立代理的工厂
                knownMappers.put(type, new MapperProxyFactory<T>(type));
                // It's important that the type is added before the parser is run
                // otherwise the binding may automatically be attempted by the mapper parser. If the type is already known, it won't try.
                //这里是解析Mapper接口里面的注解
                MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
                parser.parse();
                loadCompleted = true;
            } finally {
                if (!loadCompleted) {
                    knownMappers.remove(type);
                }
            }
        }
    }
}

mybatis使用XMLMapperBuilder类的实例来解析mapper配置文件

4.2 获取接口对象

从knownMappers中根据接口类型取出对应的代理建立工厂,用该工厂建立代理

public class MapperRegistry {
    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
                //取出MapperProxyFactory
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        if (mapperProxyFactory == null)
            throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
        try {
                        //建立代理
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new BindingException("Error getting mapper instance. Cause: " + e, e);
        }
    }
}
 
//建立代理的工厂
public class MapperProxyFactory<T> {
    /**
     * 须要建立代理的接口
     */
    private final Class<T> mapperInterface;
    /**
     * 执行方法的缓存,不须要每次都建立MapperMethod
     */
    private Map<Method, MapperMethod> methodCache = new ConcurrentHashMap<Method, MapperMethod>();
 
    public MapperProxyFactory(Class<T> mapperInterface) {
        this.mapperInterface = mapperInterface;
    }
 
    public Class<T> getMapperInterface() {
        return mapperInterface;
    }
 
    public Map<Method, MapperMethod> getMethodCache() {
        return methodCache;
    }
    @SuppressWarnings("unchecked")
    protected T newInstance(MapperProxy<T> mapperProxy) {
        //建立代理, InvocationHanderl是MapperProxy
        return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface },mapperProxy);
    }
    /**
     * 传人sqlSession建立代理
     * @param sqlSession
     * @return
     */
    public T newInstance(SqlSession sqlSession) {
        //把代理执行须要用到的对象传入
        final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
        return newInstance(mapperProxy);
    }
}

4.3 调用接口方法

调用代理方法会进入到MapperProxy的public Object invoke(Object proxy, Method method, Object[] args)方法

public class MapperProxy<T> implements InvocationHandler, Serializable {
    private static final long serialVersionUID = -6424540398559729838L;
    private final SqlSession sqlSession;
    private final Class<T> mapperInterface;
    private final Map<Method, MapperMethod> methodCache;
 
    public MapperProxy(SqlSession sqlSession, Class<T> mapperInterface, Map<Method, MapperMethod> methodCache) {
        this.sqlSession = sqlSession;
        this.mapperInterface = mapperInterface;
        this.methodCache = methodCache;
    }
 
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //若是方法是Object里面的则直接调用方法
        if (Object.class.equals(method.getDeclaringClass())) {
            try {
                return method.invoke(this, args);
            } catch (Throwable t) {
                throw ExceptionUtil.unwrapThrowable(t);
            }
        }
        //获取执行方法的封装对象
        final MapperMethod mapperMethod = cachedMapperMethod(method);
        //里面就是找到对应的sql 执行sql语句
        return mapperMethod.execute(sqlSession, args);
    }
    //缓存, 不须要每次都建立
    private MapperMethod cachedMapperMethod(Method method) {
        MapperMethod mapperMethod = methodCache.get(method);
        if (mapperMethod == null) {
            //传人配置参数
            mapperMethod = new MapperMethod(mapperInterface, method, sqlSession.getConfiguration());
            methodCache.put(method, mapperMethod);
        }
        return mapperMethod;
    }
}

最终执行sql会进入到MapperMethod中execute方法:

//具体的根据接口找到配置文件标签的类
public class MapperMethod {
 
    private final SqlCommand command;
    private final MethodSignature method;
 
    public MapperMethod(Class<?> mapperInterface, Method method, Configuration config) {
        //SqlCommand封装该接口方法须要执行sql的相关属性,如:id(name), 类型
        this.command = new SqlCommand(config, mapperInterface, method);
        //执行方法特性进行封装,用于构造sql参数,判断执行sql逻辑走哪条分支
        this.method = new MethodSignature(config, method);
    }
 
    public Object execute(SqlSession sqlSession, Object[] args) {
        Object result;
        //先找到对应的执行sql类型, sqlSession会调用不一样方法
        if (SqlCommandType.INSERT == command.getType()) {
            Object param = method.convertArgsToSqlCommandParam(args);
            result = rowCountResult(sqlSession.insert(command.getName(), param));
        } else if (SqlCommandType.UPDATE == command.getType()) {
            Object param = method.convertArgsToSqlCommandParam(args);
            result = rowCountResult(sqlSession.update(command.getName(), param));
        } else if (SqlCommandType.DELETE == command.getType()) {
            Object param = method.convertArgsToSqlCommandParam(args);
            result = rowCountResult(sqlSession.delete(command.getName(), param));
        } else if (SqlCommandType.SELECT == command.getType()) {//若是是查询, 须要对返回作判断处理
            //根据方法的特性判断进入哪一个执行分支
            if (method.returnsVoid() && method.hasResultHandler()) {
                executeWithResultHandler(sqlSession, args);
                result = null;
            } else if (method.returnsMany()) {
                result = executeForMany(sqlSession, args);
            } else if (method.returnsMap()) {
                result = executeForMap(sqlSession, args);
            } else {
                //只查一条数据
                Object param = method.convertArgsToSqlCommandParam(args);
                result = sqlSession.selectOne(command.getName(), param);
            }
        } else {
            throw new BindingException("Unknown execution method for: " + command.getName());
        }
        if (result == null && method.getReturnType().isPrimitive() && !method.returnsVoid()) {
            throw new BindingException("Mapper method '" + command.getName()
                    + " attempted to return null from a method with a primitive return type (" + method.getReturnType()
                    + ").");
        }
        return result;
    }
}

4.4 流程图

mapperProxyBuilder建立流程:

mapperProxy建立流程:

sql语句执行流程:

参考

http://www.cnblogs.com/dongying/p/4142476.html

相关文章
相关标签/搜索