随笔 - 40, 文章 - 0, 评论 - 20, 引用 - 0
数据加载中……

Ibatis示例


1.将ibatis 的jar 包添加到工程中

2.先新建一个xml文件 SqlMap.xml,在这个文件中定义使用了哪些ibatis资源文件
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE sql-map-config PUBLIC "-//iBATIS.com//DTD SQL Map Config 1.0//EN"
    "http://www.ibatis.com/dtd/sql-map-config.dtd">
<sql-map-config>
  <sql-map  resource="com/montersoft/ibatis/common/monter.xml"/>
</sql-map-config>

3.定义资源文件monter.xml
<?xml version="1.0" encoding="gb2312"?>
<!DOCTYPE sql-map
    PUBLIC "-//iBATIS.com//DTD SQL Map 1.0//EN"
    "http://www.ibatis.com/dtd/sql-map.dtd">
<sql-map name="monter">
   <result-map name="monterInfo" class="java.util.HashMap">
     <property name="id"  column="id" type="VARCHAR"/>
     <property name="name" column="name" type="VARCHAR"/>
     <property name="age"  column="age"  type="NUMBERIC"/>
   </result-map>  
   <dynamic-mapped-statement name="monter_getByPk" result-map="monterInfo">
   select id,name,age from monter where id = #id#
   </dynamic-mapped-statement>
</sql-map>

**注意dynamic-mapped-statement的name 必须唯一

4.定义一个公共类来生成SqlMap
package com.montersoft.ibatis.common;
import java.io.Reader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.ibatis.common.resources.Resources;
import com.ibatis.db.sqlmap.SqlMap;
import com.ibatis.db.sqlmap.XmlSqlMapBuilder;
public class SqlMapUtil { 
 private static Log loger = LogFactory.getLog(SqlMapUtil.class);
 public  static SqlMap  sqlMap ; 
 public static SqlMap loadSqlMap(){
  Reader reader = null;
  try{
   reader = Resources.getResourceAsReader("com/montersoft/ibatis/common/SqlMap.xml");
   return XmlSqlMapBuilder.buildSqlMap(reader);
  }
  catch(Exception e){   
   loger.error("there is a error=>"+e.getMessage());
  }
  return null;
 } 
 public static SqlMap getSqlMap(){
  if( sqlMap == null )
   sqlMap = loadSqlMap();
  return sqlMap;
 } 
}
5.再新建DAO,Vo,
public interface  IVO { 
}
public class MonterVo implements IVO{ 
 public String id ;
 public String name;
 public int age;
 ...省去 get ,set 方法
}
public class MonterDao { 
   public IVO getBkPK(Connection conn,IVO vo) throws Exception{
    try{    
    Object map  =  SqlMapUtil.getSqlMap().
       getMappedStatement("monter_getByPk").executeQueryForObject(conn,vo);
    return   copyMap2Vo(map);
    }
    catch(Exception e){       
        throw new Exception(e.getMessage());
    }
   }  
   private IVO copyMap2Vo(Object map){
    MonterVo vo = new MonterVo();
  try{
   BeanUtils.copyProperties(vo,map);
  }
  catch(Exception e){
   e.printStackTrace();
  }
  return vo;
 }
}

6.至此就建立了一个简单的ibatis示例.

posted on 2006-01-06 16:39 月亮 阅读(329) 评论(0)  编辑  收藏


只有注册用户登录后才能发表评论。


网站导航: