改造iBatis,使其支持自动生成sql语句(2)
上篇讲到基本思路和代码修改的切入点。这篇继续讲实现的细节的demo。
在生成iql语句时,generate前面和后面的iql语句给予保留,充分保留最大的灵活性。
在生成iql语句时候后,在调用insert和update时,转入的parametarObject必须是parametermap规定的Object,在select和delete时,如果parameter只有1个,则会把iql变量替换成#value#。
sql-map 代码
- <!---->xml version="1.0" encoding="UTF-8"?>
- <!---->
- "http://ibatis.apache.org/dtd/sql-map-2.dtd">
-
- <sqlMap namespace="sort">
- <typeAlias alias="Sort" type="com.cpcw.product.domain.Sort"/>
-
- <parameterMap id="SortParameterMap" class="Sort">
- <parameter property="name" column="name" jdbcType="VC"/>
- <parameter property="fid" column="fid" jdbcType="INTEGER"/>
- <parameter property="status" column="status" jdbcType="INTEGER"/>
- <parameter property="notes" column="notes" jdbcType="VC"/>
- <parameter property="created" column="created" jdbcType="TIMESTAMP"/>
- parameterMap>
-
- <parameterMap id="SortParameterFulMap" class="Sort" extends="SortParameterMap">
- <parameter property="id" column="id" jdbcType="INTEGER"/>
-
- parameterMap>
-
- <parameterMap id="SortParameterDeleteMap" class="Sort">
- <parameter property="id" column="id"/>
- parameterMap>
-
- <select id="selectSort" parameterMap="sort.SortParameterFulMap" resultClass="Sort">
- select * from (
- <generate table="sort" where="id"/>
- ) a order by id desc limit 1
- select>
-
- <insert id="createSort" parameterMap="sort.SortParameterMap">
- <selectKey keyProperty="id" resultClass="int" type="post">
- select last_insert_id() as value
- selectKey>
- <generate table="sort"/>
- insert>
- <update id="updateSort" parameterMap="sort.SortParameterFulMap">
- <generate where="id" table="sort" excludes="{status,created}"/>
- update>
-
- <delete id="deleteSort" parameterMap="sort.SortParameterDeleteMap">
- <generate table="sort" where="id"/>
- delete>
-
-
- sqlMap>
java 代码
- public Sort getSortById(int id) {
- return (Sort) queryForObject("sort.selectSort", new Integer(id));
- }
-
- public int createSort(Sort sort) {
- insert("sort.createSort", sort);
- return sort.getId();
- }
-
- public int updateSort(Sort sort) {
- return update("sort.updateSort", sort);
- }
-
- public int deleteSort(int id) {
- return delete("sort.deleteSort", new Integer(id));
- }
生成的IQL 代码
- select:
- select * from (
- select name as name, fid as fid, status as status, notes as notes, created as created, id as id from sort where id = #value#
- ) a order by id desc limit 1
-
- inesrt:
- insert into sort (name, fid, status, notes, created) values (#name:VC#, #fid:INTEGER#, #status:INTEGER#, #notes:VC#, #created:TIMESTAMP#)
-
- update:
- update sort set name = #name:VC#, fid = #fid:INTEGER#, notes = #notes:VC#, id = #id:INTEGER# where id = #id:INTEGER#
- delete
- delete from sort where id = #value#
原创文章,如果要转载请注明出处、原始地址和作者信息。