iBATIS实例的创建是什么过程呢?让我们开始我们的讲述:
iBATIS实例创建第一步:
将iBATIS的jar 包添加到工程中
iBATIS实例创建第二步
新建一个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﹥
iBATIS实例创建第三步:
定义资源文件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 必须唯一
iBATIS实例创建第四步:
定义一个公共类来生成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;
- }
- }
iBATIS实例创建第五步
新建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;
- }
- }
iBATIS实例至此就建立了,那么通过这个简单的实例是不是对iBATIS实例的建立有了更明确的认识呢?
【编辑推荐】