文末附有源码地址
介绍:博客为代码完成后才开始整理,展示的代码都是最终代码
个人学习,代码写的不够好,有点乱
通过学习mybatis源码模拟实现Mybatis(在完善)
已实现:
crud(实现XML配置,注解配置写过一点,原理差不多不写了)、
事务、
数据库连接池、
动态sql(一部分,原理没问题了,以后有时间再完善)、
一级二级缓存
此篇动态sql代码因时间缘故并没有完全完成。
一、配置Mybatis中的动态SQL技术和 ${param}运用了OGNL。本文便不再介绍ognl。
首先我们来看一下mybatis动态sql的xml
select * from `user` where username LIKE #{username} and username LIKE #{username} and sex = #{sex}
我们所要做的是将if中的test的语句判断出来,由判断出来的结果来确定是否要将下面的语句进行拼接。
我们由下面这个类开始构建sql,并没有完全完成
public class XMlSqlBuilder {
public static String sqlParser(Element element, Object[] object) {
StringBuilder sb = new StringBuilder();
List nodes = element.selectNodes("node()");
for (Node n : nodes) {
if (n.getNodeTypeName() == "Text") {
sb.append(n.getText());
} else {
try {
sb.append(OgnlParser((Element) n, object));
} catch (OgnlException e) {
e.printStackTrace();
}
}
}
return sb.toString();
}
public static String OgnlParser(Element e, Object[] object) throws OgnlException {
StringBuilder resultStr = new StringBuilder();
String str = e.getName();
if (str.equals("if")) {
String attribute = e.attributevalue("test");
boolean result = (boolean) Ognl.getValue(attribute, object[0]);
if (result) {
resultStr.append(e.getText());
}
} else if (str.equals("foreach")) {
} else if (str.equals("where")) {
List elements = e.elements();
StringBuilder tempSb = new StringBuilder();
for (Element ele : elements) {
tempSb.append(OgnlParser(ele, object));
}
String temp = tempSb.toString().trim();
if (temp.length() > 0) {
resultStr.append(" where ");
if (temp.indexOf("AND") == 0 || temp.indexOf("and") == 0 || temp.indexOf("OR") == 0 || temp.indexOf("or") == 0) {
temp.substring(0, 3);
}
if (temp.indexOf("OR") == 0 || temp.indexOf("or") == 0) {
temp.substring(0, 2);
}
resultStr.append(" " + temp);
}
}
return resultStr.toString();
}
}
其中
boolean result = (boolean) Ognl.getValue(attribute, object[0]);
获取了判断结果。然后将sql拼接。
项目地址github:https://github.com/Alice-175/Mybaits
gitee:https://gitee.com/alice-175/Mybaits



