ITeye博客

ibatis 如何直接执行sql语句

J2EE大鸟 · 2012-11-18 18:47 · javaweb应用问题解决 · javaweb J2EE · 编程语言 · Markdown

终于弄出来了,不过好像绕了一个大圈,同事跟我说,ibatis 配置文件中 select 标签,不可以执行Mysql中的show 语句(SHOW TABLE STATUS FROM 数据库名),结果找的时候,压根没想到 select 标签可以执行 show 语句。下面贴下完整的代码

DbSize.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE sqlMap PUBLIC "-//iBATIS.com//DTD SQL Map 2.0//EN" "http://www.ibatis.com/dtd/sql-map-2.dtd">
 
<sqlMap namespace="DbSize">
    <typeAlias alias="dbSize" type="com.telin.domain.DbSize" />
    <resultMap id="dbSizeResult" class="dbSize">
        <result property="rows" column="Rows" />
        <result property="dateLength" column="Data_length" />
        <result property="indexLength" column="Index_length" />
    </resultMap>
     
    <select id="getDbSize" resultMap="dbSizeResult" parameterClass="string">   
          <![CDATA[   $sql$   ]]>
      </select>
 
</sqlMap>

 对ibatis学艺不精,不知道虚拟表也可以这样进行字段映射,只要列名对应Bean中的属性即可
这里特别要注意  $sql$ 这句

DAO层中的方法

public float getDbSize( Properties properties, String companyId ) throws Exception{
        float dbsize = 0;
         
        String sql = "SHOW TABLE STATUS FROM dbu_" + companyId.trim() + " " +
                    "WHERE Name like 'bbs_%' " +
                    "or Name like 'dbu_%' " +
                    "or Name like 'phpbbs_%'";
 
        //获取数据库连接
        this.getSqlMapClientbyProperty(properties); 
        List<DbSize> list = null;
        list = sqlMapClient.queryForList( "getDbSize", sql );
         
        float tempsize = 0;
        //获取数据库容量大小
        Iterator it = list.iterator();
        while( it.hasNext() ){
            DbSize sizeBean = ( DbSize )it.next();
            tempsize = tempsize + sizeBean.getDateLength();
            tempsize = tempsize + sizeBean.getIndexLength();
        }
        dbsize = tempsize / 1048576; //1048576 = 1024*1024
         
        return dbsize;
    }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。