注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

IOS & JAVA KEY

(iMilo)

 
 
 

日志

 
 
关于我

All the splendor in the world is not worth a good friend!! Hello my friend!!

网易考拉推荐

iBATIS操作Blob与Clob浅析  

2011-07-16 16:30:54|  分类: webservice |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

引入:

这几天仔细看了一下iBATIS的文档,发现2.2后,iBATIS的改变还是挺大的。对于自定义类型支持的也不错,这样对于blobClob数据的处理也就简单多了。

 

不过在spring 中已经提供了很好的实现,所以这又省去了很多的功夫,接下来看看iBATIS是如何支持Clobblob的。

 

iBATIS提供了TypeHandler接口,用于处理数据类型,基本的实现类为BaseTypeHandler

 

spring 中,提供了AbstractLobTypeHandler作为基础类,并且提供了相应的模版方法,所有的工作由LobHandler处理。

 

BlobByteArrayTypeHandler 主要用于处理blob类型数据,使用byte[]来映射相应的Blob

 

ClobStringTypeHandler 用于处理Clob类型数据,使用字符串来映射Clob

 

有一点需要注意的是,AbstractLobTypeHandler中实现了事务支持,需要用来释放相应的资源,所以一定需要在事务环境中进行。

实例:

1VO

package com.teana.vo;

 

import java.io.Serializable;

import java.util.Arrays;

import java.util.Date;

 

/**

 * @author TEANA E-mail: mmz06@163.com

 * @version 创建时间:2011-7-16 上午10:38:58

 * @DO      演示多个数据类型包括(blob        

 */

 

public class GCUFood implements Serializable

{

    private static final long serialVersionUID = 1376693920628504436L;

   

    private int fdID;

    private String fdName;

    private byte[] image;

    private boolean isNew;

    private Date createD;

    private Date updateDT;

    private double prices;

    private int counts;

   

    public GCUFood()

    {

        super();

    }

 

    public GCUFood(int fdID, String fdName, byte[] image, boolean isNew,

            Date createD, Date updateDT, double prices, int counts)

    {

        super();

        …………

    }

 

    set*** get***

}

2VO对应的ibatisxml文件

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE sqlMap     

    PUBLIC "-//ibatis.apache.org//DTD SQL Map 2.0//EN"     

    "http://ibatis.apache.org/dtd/sql-map-2.dtd">

<sqlMap namespace="foodNS">

    <resultMap class="Food" id="FoodMap">

        <result property="fdID" column="FDID" />

        <result property="fdName" column="FDNAME" />

        <result property="image" column="IMAGE"

            typeHandler="org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler" />

        <result property="isNew" column="ISNEW" />

        <result property="createD" column="CREATED" />

        <result property="updateDT" column="UPDATEDT" />

        <result property="prices" column="PRICES" />

        <result property="counts" column="COUNTS" />

    </resultMap>

    <!-- 通过ID查询食物 -->

    <select id="findByID" parameterClass="int" resultMap="FoodMap">

        SELECT F.FDID,F.FDNAME,F.IMAGE,F.ISNEW,

        F.CREATED,F.UPDATEDT,F.PRICES,F.COUNTS

        FROM TB_FOOD F

        WHERE F.FDID = #fdID#

    </select>

    <!-- 查询所有食物-->

    <select id="findAll" resultMap="FoodMap">

        SELECT F.FDID,F.FDNAME,F.IMAGE,F.ISNEW,

        F.CREATED,F.UPDATEDT,F.PRICES,F.COUNTS

        FROM TB_FOOD F

    </select>

    <!-- 添加食品 -->

    <insert id="add" parameterClass="Food">

        INSERT INTO TB_FOOD(FDID,FDNAME,IMAGE,ISNEW,CREATED,UPDATEDT,PRICES,COUNTS)

        VALUES(#fdID#,#fdName#,

        #image,handler=org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler#,

        #isNew#,#createD#,#updateDT#,#prices#,#counts#)

    </insert>

    <!-- 更新食品 -->

    <update id="update" parameterClass="Food">

        UPDATE TB_FOOD SET

        FDNAME = #fdName#,

        <dynamic prepend="">

            <isNotNull property="image" prepend="">

                IMAGE = #image,handler=org.springframework.orm.ibatis.support.BlobByteArrayTypeHandler#,

            </isNotNull>

        </dynamic>

        ISNEW = #isNew#,

        CREATED = #createD#,

        UPDATEDT = #updateDT#,

        PRICES = #prices#,

        COUNTS = #counts#

        WHERE FDID = #fdID#

    </update>

</sqlMap>

3DAO层实现

package com.teana.dao.impl;

 

import java.util.List;

 

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

 

import com.ibatis.sqlmap.client.SqlMapClient;

import com.teana.dao.GCUFoodDAO;

import com.teana.vo.GCUFood;

 

/**

 * @author TEANA E-mail: mmz06@163.com

 * @version 创建时间:2011-7-16 上午11:06:26

 * @DO              

 */

 

public class GCUFoodDAOBean implements GCUFoodDAO

{

    private static final Log log = LogFactory.getLog(GCUFoodDAOBean.class);

    private SqlMapClient client;

   

    public void setClient(SqlMapClient client)

    {

        this.client = client;

    }

    public GCUFood findByID(int fdID)

    {

        log.debug("finding Food by userID =  " + fdID);

        try

        {

            return (GCUFood) client.queryForObject("foodNS.findByID", fdID);

        }

        catch(Exception re)

        {

            log.error("find Food by fdID = " + fdID +  "failed", re);

            return null;

        }

    }

 

    @SuppressWarnings("unchecked")

    public List<GCUFood> findAll()

    {

        log.debug("finding List<GCUFood>");

        try

        {

            return client.queryForList("foodNS.findAll");

        }

        catch(Exception re)

        {

            log.error("find List<GCUFood> failed", re);

            return null;

        }

    }

    public boolean add(GCUFood food)

    {

        log.debug("adding Food =  " + food);

        int rows = 0;

        try

        {

            rows = (Integer) client.insert("foodNS.add", food);

            log.debug("Food [ rows = " + rows + " ]");

            if(rows == 1)

            {

                return true;

            }

            return false;

        }

        catch(Exception re)

        {

            log.error("adding Food = " + food +  " failed !", re);

            return false;

        }

    }

    public boolean update(GCUFood food)

    {

        log.debug("update Food -- food = " + food);

        boolean flag = false;

        int rows = 0;

        try

        {

            rows = client.update("foodNS.update", food);

            if(1 == rows)

                flag = true;

            return flag;

        }

        catch(Exception re)

        {

            log.error("updating Food -- food = " + food + " failed", re);

            return false;

        }

    }

 

}

4spring配置

<?xml version="1.0" encoding="UTF-8"?>

<beans

    xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

   

     <bean id="propertyConfigurer"   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

        <property name="location">

            <value>classpath:com/teana/config/jdbc.properties</value>

        </property>

     </bean>

     

     <bean id="lobHandler"

        class="org.springframework.jdbc.support.lob.DefaultLobHandler" />

     

     <bean id="dataSource"

        class="org.apache.commons.dbcp.BasicDataSource">

        <property name="driverClassName" value="${mysql.driver}" />

        <property name="url" value="${mysql.url}" />

        <property name="username" value="${mysql.username}" />

        <property name="password" value="${mysql.password}" />

    </bean>

   

    <bean id="client"

        class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">

        <property name="dataSource">

            <ref local="dataSource"/>

        </property>

        <property name="configLocation">

            <value>classpath:com/teana/config/ibatis-config.xml</value>

        </property>

        <property name="lobHandler">

            <ref local="lobHandler" />

        </property>

    </bean>

 

    <bean id="foodDAO" class="com.teana.dao.impl.GCUFoodDAOBean">

        <property name="client" ref="client" />

    </bean>

    <bean id="foodService" class="com.teana.service.impl.GCUFoodServiceBean">

        <property name="foodDAO" ref="foodDAO" />

    </bean>

</beans>

5、简单测试(这里只是简单对数据库中取得所有数据进行说明)

package com.teana.service.impl;

 

import java.io.FileOutputStream;

import java.io.IOException;

import java.util.List;

 

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

 

import com.teana.dao.GCUFoodDAO;

import com.teana.service.GCUFoodService;

import com.teana.vo.GCUFood;

 

/**

 * @author TEANA E-mail: mmz06@163.com

 * @version 创建时间:2011-7-16 上午11:23:16

 * @DO              

 */

public class GCUFoodServiceBean implements GCUFoodService

{

    private static final Log log = LogFactory.getLog(GCUFoodServiceBean.class);

    private GCUFoodDAO foodDAO;

   

    public void setFoodDAO(GCUFoodDAO foodDAO)

    {

        this.foodDAO = foodDAO;

    }

 

    public GCUFood findByID(int fdID)

    {

        return foodDAO.findByID(fdID);

    }

 

    public List<GCUFood> findAll()

    {

        List<GCUFood> foods = foodDAO.findAll();

        save(foods);

        return foods;

    }

   

    protected void save( List<GCUFood> foods)

    {

        for(GCUFood food : foods)

        {

            log.debug("foods bytes is " + (food.getImage().length));

            /*

            for(int i = 0; i <food.getImage().length; i++)

            {

                log.debug("image["  + i + "] = " + food.getImage()[i]);

            }

            */

            FileOutputStream fos = null;

            try

            {

                fos = new FileOutputStream("D:/image_" + food.getFdID() + ".jpg");

                fos.write(food.getImage());

            }

            catch (IOException e)

            {

                e.printStackTrace();

            }

            finally

            {

                try{

                        fos.close();

                    }catch(Exception e){}

            }

        }

    }

 

    public boolean add(GCUFood food)

    {

        return foodDAO.add(food);

    }

 

    public boolean update(GCUFood food)

    {

        return foodDAO.update(food);

    }

}

参考

iBATIS操作BlobClob浅析

其他

2011-07-16

iMilo

 

 

  评论这张
 
阅读(1835)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017