Mybatis 连接Oracle 存取图片到blob字段

项目上碰到了blob存取图片视频到大字段blob的问题,网上一对办法基本都不能满足要求,没办法,不自己动手的咸鱼不是好咸鱼

 

首先创建一张表

 

使用mybatis-generator插件自动生成 mapper.xml,dao,entity

PicInfoMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.zkyt.lyggis.dao.PicInfoMapper" >
  <resultMap id="BaseResultMap" type="com.zkyt.lyggis.model.PicInfo" >
    <id column="ID" property="id" jdbcType="VARCHAR" />
  </resultMap>
  <resultMap id="ResultMapWithBLOBs" type="com.zkyt.lyggis.model.PicInfo" extends="BaseResultMap" >
    <result column="IMG" property="img" jdbcType="BLOB" />
    <result column="VIDEO" property="video" jdbcType="BLOB" />
  </resultMap>
  <sql id="Base_Column_List" >
    ID
  </sql>
  <sql id="Blob_Column_List" >
    IMG, VIDEO
  </sql>
  <select id="selectByPrimaryKey" resultMap="ResultMapWithBLOBs" parameterType="java.lang.String" >
    select 
    <include refid="Base_Column_List" />
    ,
    <include refid="Blob_Column_List" />
    from PIC_INFO
    where ID = #{id,jdbcType=VARCHAR}
  </select>
  <delete id="deleteByPrimaryKey" parameterType="java.lang.String" >
    delete from PIC_INFO
    where ID = #{id,jdbcType=VARCHAR}
  </delete>
  <insert id="insert" parameterType="com.zkyt.lyggis.model.PicInfo" >
    insert into PIC_INFO (ID, IMG, VIDEO)
    values (#{id,jdbcType=VARCHAR}, #{img,jdbcType=BLOB}, #{video,jdbcType=BLOB})
  </insert>
  <insert id="insertSelective" parameterType="com.zkyt.lyggis.model.PicInfo" >
    insert into PIC_INFO
    <trim prefix="(" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        ID,
      </if>
      <if test="img != null" >
        IMG,
      </if>
      <if test="video != null" >
        VIDEO,
      </if>
    </trim>
    <trim prefix="values (" suffix=")" suffixOverrides="," >
      <if test="id != null" >
        #{id,jdbcType=VARCHAR},
      </if>
      <if test="img != null" >
        #{img,jdbcType=BLOB},
      </if>
      <if test="video != null" >
        #{video,jdbcType=BLOB},
      </if>
    </trim>
  </insert>
  <update id="updateByPrimaryKeySelective" parameterType="com.zkyt.lyggis.model.PicInfo" >
    update PIC_INFO
    <set >
      <if test="img != null" >
        IMG = #{img,jdbcType=BLOB},
      </if>
      <if test="video != null" >
        VIDEO = #{video,jdbcType=BLOB},
      </if>
    </set>
    where ID = #{id,jdbcType=VARCHAR}
  </update>
  <update id="updateByPrimaryKeyWithBLOBs" parameterType="com.zkyt.lyggis.model.PicInfo" >
    update PIC_INFO
    set IMG = #{img,jdbcType=BLOB},
      VIDEO = #{video,jdbcType=BLOB}
    where ID = #{id,jdbcType=VARCHAR}
  </update>
</mapper>

PicInfoMapper.java(dao):


public interface PicInfoMapper {
    int deleteByPrimaryKey(String id);

    int insert(PicInfo record);

    int insertSelective(PicInfo record);

    PicInfo selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(PicInfo record);

    int updateByPrimaryKeyWithBLOBs(PicInfo record);
}

PicInfo.java(entity)


public class PicInfo {
    private String id;

    private byte[] img;

    private byte[] video;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id == null ? null : id.trim();
    }

    public byte[] getImg() {
        return img;
    }

    public void setImg(byte[] img) {
        this.img = img;
    }

    public byte[] getVideo() {
        return video;
    }

    public void setVideo(byte[] video) {
        this.video = video;
    }
}

service(接口)


public interface PicInfoService {
    PicInfo findById(String id);

    int addPic(PicInfo picInfo);
}

serviceImpl(service实现)



@Service
public class PicInfoServiceImpl implements PicInfoService {
    @Resource
    private PicInfoMapper picInfoMapper;
    @Override
    public PicInfo findById(String id) {
        return picInfoMapper.selectByPrimaryKey(id);
    }

    @Override
    public int addPic(PicInfo picInfo) {
        return picInfoMapper.insertSelective(picInfo);
    }
}

controller


@Controller
@RequestMapping("/pic")
public class PicInfoController extends BaseController {
    @Resource
    private PicInfoService picInfoService;

    @RequestMapping("add")
    @ResponseBody
    public void add(PicInfo picInfo){
        JSONObject json = new JSONObject();
        String pic = "F:\\1.jpg";//这里暂时放一张本地图片,也可以让前台传过来
        File file = new File(pic);
        try{
            InputStream is=new FileInputStream(file);//得到文件流
            byte[] bytes = FileCopyUtils.copyToByteArray(is);//得到byte
            picInfo.setId(UUIDsupport.getUUIDWithoutMinus());
            picInfo.setImg(bytes);
            int add =  picInfoService.addPic(picInfo);//添加到数据库中
            if (add > 0) {
                json.put("add", add);
                json.put("msg","上传成功");
            }else {
                json.put("msg","上传失败");
            }
            toClient(json.toString());
        }catch (IOException e) {
            logger.info("异常信息",e);
        }
    }
}

BaseController


/**
 * @ClassName BaseController
 * @Description controller(基类)
 * @author tangjp
 */
public abstract class BaseController<T> {
    protected final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * ThreadLocal确保高并发下每个请求的request,response都是独立的
     */
    private static ThreadLocal<ServletRequest> currentRequest = new ThreadLocal<ServletRequest>();
    private ThreadLocal<ServletResponse> currentResponse = new ThreadLocal<ServletResponse>();
    private ThreadLocal<BasePage<T>> currentPagination = new ThreadLocal<BasePage<T>>();
    // 获得请求对象
    public HttpServletRequest request;
    // 获取取响应对象
    public HttpServletResponse response;
    // 设置mvc常用变量
    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        response.setHeader("Access-Control-Allow-Origin", "*");
        this.request = request;
        this.response = response;
    }
    protected BasePage<T> getPagination() {
        return currentPagination.get();
    }

    public void toClient(String str) {
        PrintWriter out = null;
        try {
            response.setHeader("Content-Type", "text/html;charset=UTF-8");
            out = response.getWriter();
            out.print(str);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.flush();
                out.close();
                out = null;
            }
        }
    }

}

这样就可以插入图片了,读取等下次来写吧。。。。

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MyBatis提供了Blob类型的支持,可以将二进制数据(如图片)存储到OracleBlob字段中。 首先,在Mapper.xml中定义一个insert语句,如下所示: ``` <insert id="insertImage" parameterType="Map"> INSERT INTO image_table(id, image) VALUES(#{id}, #{image,jdbcType=BLOB}) </insert> ``` 其中,#{image,jdbcType=BLOB}表示将image属性映射到数据库的BLOB字段。 然后,在Java代码中,将图片转换成字节数组,再将字节数组封装到一个Map中,作为参数调用insertImage方法,如下所示: ``` byte[] imageBytes = Files.readAllBytes(Paths.get("path/to/image.png")); Map<String, Object> paramMap = new HashMap<>(); paramMap.put("id", 1); paramMap.put("image", imageBytes); mapper.insertImage(paramMap); ``` 以上代码将读取一个PNG格式的图片文件,将其转换成字节数组,然后将字节数组封装到一个Map中,作为参数调用insertImage方法,将图片存储到数据库中。 查询Blob类型的数据时,可以使用MyBatis提供的ResultHandler接口来处理Blob类型的数据,如下所示: ``` public class ImageResultHandler implements ResultHandler { @Override public void handleResult(ResultContext context) { ImageEntity entity = (ImageEntity) context.getResultObject(); Blob blob = entity.getImage(); byte[] bytes = null; try (InputStream inputStream = blob.getBinaryStream()) { bytes = IOUtils.toByteArray(inputStream); } catch (SQLException | IOException e) { e.printStackTrace(); } entity.setImageBytes(bytes); } } public interface ImageMapper { @Select("SELECT id, image FROM image_table WHERE id=#{id}") @ResultType(ImageEntity.class) void getImage(long id, ResultHandler handler); } ``` 以上代码定义了一个ImageResultHandler类,实现了ResultHandler接口,用于处理查询结果中的Blob类型数据。在调用ImageMapper的getImage方法时,将ImageResultHandler实例作为参数传入,MyBatis会自动调用ImageResultHandler的handleResult方法,将查询结果封装成ImageEntity实例。 在ImageEntity类中,可以定义一个byte[]类型的属性,用于存储从Blob字段中读取的字节数组。这样,查询到的图片数据就可以直接使用了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值