由于一直是做web端,最近接触android,操作数据库的时候怀念mybatis,因此很简单的做了个功能有限的仿造。在此来探讨一下。
mybatis对于sql还是需要写的,只是自动映射字段到结果对象,所以是半自动,以此来体现其灵活性。而对于sql的管控完全分离到了xml之中。其中最令人印象深刻的地方之一应该是通过一个mapper接口去和xml进行管理。而这个mapper接口你只需要定义方法,系统会自动实现你的接口。
动态实现接口,其实原理是动态代理。通过把该接口代理为一个操作数据库的工具类,并通过xml解析,把sql传入到工具类执行sql,再通过反射进行对象映射即可。
我们来看一下我的实现吧,为了理解,先看一下xml
1、用来建表,删除表的xml
<db>
<table name="t_task">
<colunm name="id" type="varchar(64)" primaryKey="true"/>
<colunm name="title" type="varchar(30)"/>
<colunm name="brief" type="text"/>
<colunm name="beginTime" type="datetime"/>
<colunm name="repeat" type="varchar(30)"/>
<colunm name="requestCode" type="varchar(30)"/>
<colunm name="isRun" type="varchar(8)"/>
</table>
</db>
2、sql操作的xml
<mapper namespace="com.xf.ztime.task.mapper.TaskMapper">
<select id="findTask" resultType="com.xf.ztime.task.model.TaskVo">
select id,title,brief,isRun,beginTime,repeat,requestCode
from t_task
limit ${rows} offset ${offset}
</select>
<select id="findById" resultType="com.xf.ztime.task.model.TaskVo">
select id,title,brief,isRun,beginTime,repeat,requestCode
from t_task
where id='${id}'
</select>
<select id="findByRequestCode" resultType="com.xf.ztime.task.model.TaskVo">
select id,title,brief,isRun,beginTime,repeat,requestCode
from t_task
where requestCode='${requestCode}'
</select>
<insert id="insert">
insert into t_task
(id,title,brief,beginTime,repeat,requestCode,isRun)
values('${id}','${title}','${brief}','${beginTime}','${repeat}','${requestCode}','${isRun}')
</insert>
<update id="update">
update t_task
set title='${title}',
brief='${brief}',
beginTime='${beginTime}',
repeat='${repeat}'
where id='${id}'
</update>
<update id="updateRun">
update t_task
set isRun='${isRun}'
where id='${id}'
</update>
<delete id="delete">
delete from t_task
where id='${id}'
</delete>
</mapper>
3、动态代理核心代码
/**
*
* 仿造mybaits,通过动态代理将xml和mapper绑定,并解析xml执行sql
*
* @author 吴林峰
*
*/
public class Loader implements InvocationHandler{
private static String TAG="Loader";
private Helper helper;
public static String dbPath;
private static final String MAPPER_NAMESPACE="namespace";
private static final String ID="id";
private static final String TABLE_NAME="name";
private static final String COLUNM_NAME="name";
private static final String COLUNM_TYPE="type";
private static final String COLUNM_PRIMARY="primaryKey";
priva