SQL基础:java mybatis动态sql实现逻辑代码详解
mybatis通过将sql配置xml文件中,通过解析xml动态标签来实现动态sql
如下样例 xml文件
<?xml version = "1.0" ?> <!DOCTYPE script SYSTEM "script-1.0.dtd"> <script namespace="user"> <common id="commonOrder"> order by id desc </common> <sql id="queryUser"> select * from user <where> <if test='id != null '> id = #{id} </if> <if test="names != null and names.size() >0"> and name in <foreach collection="names" item="item" separator="," open="(" close=")"> ${item} </foreach> </if> </where> <ref id="commonOrder"/> </sql> <sql id="updateUser"> update user set name = ${name} <where> <if test='id != null '> id = #{id} </if> </where> </sql> </script>
1.xml文件读取
xml标签编写规则
<!ELEMENT script (#PCDATA | sql | common)*> <!ATTLIST script namespace CDATA #REQUIRED > <!ELEMENT sql (#PCDATA | trim | where | set | foreach | choose | if | ref)*> <!ATTLIST sql id CDATA #REQUIRED > <!ELEMENT common (#PCDATA | trim | where | set | foreach | choose | if)*> <!ATTLIST common id CDATA #REQUIRED > <!ELEMENT ref (#PCDATA)*> <!ATTLIST ref id CDATA #REQUIRED > <!ELEMENT trim (#PCDATA | trim | where | set | foreach | choose | if)*> <!ATTLIST trim prefix CDATA #IMPLIED prefixOverrides CDATA #IMPLIED suffix CDATA #IMPLIED suffixOverrides CDATA #IMPLIED > <!ELEMENT where (#PCDATA | trim | where | set | foreach | choose | if | ref)*> <!ELEMENT set (#PCDATA | trim | where | set | foreach | choose | if)*> <!ELEMENT foreach (#PCDATA | trim | where | set | foreach | choose | if)*> <!ATTLIST foreach collection CDATA #REQUIRED item CDATA #IMPLIED index CDATA #IMPLIED open CDATA #IMPLIED close CDATA #IMPLIED separator CDATA #IMPLIED > <!ELEMENT choose (when* , otherwise?)> <!ELEMENT when (#PCDATA | trim | where | set | foreach | choose | if)*> <!ATTLIST when test CDATA #REQUIRED > <!ELEMENT otherwise (#PCDATA | trim | where | set | foreach | choose | if)*> <!ELEMENT if (#PCDATA | trim | where | set | foreach | choose | if)*> <!ATTLIST if test CDATA #REQUIRED >
DocumentBuilderFactory 是jdk自带的解析xml文件操作,位于 javax.xml.parsers 包,如图其是一个抽象类,因此无法被实例化
需要通过 newInstance 来实例化
实例化对象后的属性 setValidating(true); 即通过xml的 验证规则进行xml格式验证
2.xml 文件解析
到此这篇关于mybatis动态sql实现逻辑代码详解的文章就介绍到这了,更多相关mybatis动态sql内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!